#!/bin/bash
#
# agsatellite - wrapper script for AGSatellite. 
#
#set -x

USAGE="Usage: $0 [-h|--help] [-k|--kill] [-v|--version] [-g|--gold] [-r|--restart] [-d|--daemon]"
VERSION=`cat /usr/lib/agsatellite/version`

RCNAME=".agsatellite"
RCDIR=${HOME}/${RCNAME}
UPSTREAMBIN=/usr/bin/AGSatellite

# restart timer
restart=${restart:=60}

# mentioned in FAQ; linux clients have connect with this "<IP> <Port>"
# := sets default value
options=${options:=64.245.58.81 21}

run_cmd () {
	if [ x != "x$do_restart" ] ; then
		while true; do ${UPSTREAMBIN} ${options} ; sleep ${restart}; done
	elif [ x != "x$do_backgrd" ] ; then
		${UPSTREAMBIN} ${options} &
	else 
		${UPSTREAMBIN} ${options}
	fi
}

run_kill () {
	killall `which AGSatellite` > /dev/null 2>&1
}

TEMP=`getopt -o hvkgdr:: -l help,version,kill,gold,daemon,restart:: \
	-n $0 -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
	case "$1" in
		-h|--help) echo ${USAGE}; exit 0;;
		-v|--version) echo "$0 v${VERSION}" ; exit 0;;
		-k|--kill) run_kill; exit 0;;
		-g|--gold) options="64.245.59.147 21" ; shift ;;
		-r|--restart) do_restart=yes;
			case "$2" in
				"") if [ -z $2 ] && [ x != "x$4" ]; then 
					  restart=$4;
				    fi
				    shift 2 ;;
				*) restart=$2 ; shift 2 ;;
			esac ;;
		-d|--daemon) do_backgrd=yes ; shift ;;
		--) shift ; break ;;
	    *) echo "Internal error!" >&2
		   echo "$USAGE" >&2
		   exit 2 ;;
	esac
done

# rest of arguments
for arg do echo -n "" ; done

trap 'run_kill; exit 1' 1 2 3 15

# Let's see if everything is in the right place
if [ ! -e ${RCDIR} ]; then
	echo -n "creating ${RCNAME} directory"
	mkdir ${RCDIR}
	chmod 700 ${RCDIR}
fi

# since 'AGSatellite' dosn't look in multiple directory for rcfiles we 
# have to enshure that 'AGSatellite' has it's environment in './'
cd $RCDIR
if [ ! -e account.txt ]; then
	echo "No `pwd`/account.txt file. Create it with 'agsatellite-config'."
	exit 1
fi
if [ ! -e shares.txt ]; then
	echo "OMG, `pwd`/shares.txt file doesn't exist. Go create it."
	exit 1
fi

run_cmd
exit 0

