#!/bin/sh

defaultconfig=$(dirname $0)/hosts

function usage(){
	echo "Usage: $(basename $0) [-c <config>] [-u <user>] <command>"
}

TEMP=`getopt -o h,u:,c: --long help,user:,config: -n $(basename $0) -- "$@"`
if [ $? != 0 ] ; then
        usage
	exit 1
fi
eval set -- "$TEMP"

user=msmeasure
config=$defaultconfig
while true ; do
        case "$1" in
		-h|--help)
			usage; exit 0;
		;;
		-c|--config)
			if [ -f "$2" ] ; then
				config=$2
			else
				echo "Configuration file $2 not found!" >&2
			fi
			shift 2
		;;
		-u|--user)
			if [ ! -z "$2" ] ; then
				user=$2
			else
				echo "Invalid user '$2'!" >&2
			fi
			shift 2
		;;
		--)
			shift
			break
		;;
		*)
			echo "Internal error!: \"$1\"" >&2
			exit 1
		;;
			
	esac
done

if [ -f "$config" ] ; then
	hosts=$(grep connection $config | perl -ne 's/connection=\s*//; s/-/ /g; print')
else
	echo "Config not found." >&2
	exit 1
fi

echo "Command: $@"
for i in $hosts ; do
	echo -n "Executing command on host $i: "
	ssh $user@$i "$@" && echo -e " \033[01;32mDone.\033[00m" || echo -e " \033[01;31mFailed.\033[00m"
done
