#!/bin/sh



usage(){
	echo "Usage: $(basename $0) [-c <config>] -s src [-d dst]"
}

defaultconfig=$(dirname $0)/hosts

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

src=
dst=/tmp
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
		;;
		-s|--src)
			if [ -f "$2" ] ; then
				src=$2
			else
				if [ -d "$2" ] ; then
					src=$2
				else
					echo "Source $2 not found!" >&2
					exit 1
				fi
			fi
			shift 2
		;;
		-d|--dst)
			if [ ! -z "$2" ] ; then
				dst=$2
			else
				echo "No destination given. Using $dst!" >&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

if [ -f "$src" -o -d "$src" ] ; then
	if [ -d "$src" ] ; then
		src="-r $src"
	fi
	for i in $hosts ; do
		echo -e "\033[01;33mCopying $src to $i:$dst...\033[00m"
		scp -r $src msmeasure@$i:$dst && echo -e "\033[01;32mDone.\033[00m" || echo -e "\033[01;31mFailed.\033[00m"
	done
else
	echo "No source given!" >&2
	usage
	exit 1
fi
