#!/bin/sh



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

defaultconfig=$(dirname $0)/hosts

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

src=$HOME/voicehoc/benchmarksources/
dst=/home/msmeasure/voicehoc/
config=$defaultconfig
remove=

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
		;;
		-r|--remove)
			remove="--delete"
			shift
		;;
		--)
			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
	for i in $hosts ; do
		echo -e "\033[01;33mSyncing $src to $i:$dst...\033[00m"
		rsync -az $remove $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
