#!/bin/sh

SERVER_HOST="maxi"
SERVER_PORT=80
BASE_DOWNLOAD_URL="http://$SERVER_HOST:$SERVER_PORT/public/files/compro"
INSTALL_DIR="/GDClient"
SCRIPT_NAME="gdclient_compro.sh"
CONFIG_FILE_NAME="GDClient.cfg"

downloadFile() {
	rm $1
	wget $BASE_DOWNLOAD_URL/$1 -O $1
	result=$?
	chmod +x $1
	return $result
}

downloadAll() {
	downloadFile "GDClient"
	if [ $? -ne 0 ]; then return 5; fi
	downloadFile "GDClient.cfg"
	if [ $? -ne 0 ]; then return 5; fi
	mkdir -p "scripts"
	downloadFile "scripts/showlogs.sh"
	if [ $? -ne 0 ]; then return 5; fi

	return 0
}

trap '$LOGGER "Caught signal from GDClient."' INT ILL ABRT KILL SEGV PIPE TERM  

main() {
	current_dir=`pwd`
	mkdir -p $INSTALL_DIR
	cd $INSTALL_DIR

	while [ 1 ]
	do
		killall GDClient
	
		while [ 1 ]
		do
			downloadAll
			result=$?
			if [ $result -ne 0 ]
			then
				$LOGGER "Failed to download $BASE_DOWNLOAD/$DOWNLOAD_FILENAME. Retrying download in $result seconds..."
				sleep $result 
			else
				break
			fi
		done

		if [ -e "$INSTALL_DIR/GDClient" ]
		then
			while [ 1 ]
			do
				echo $1
				$INSTALL_DIR/GDClient $1 $INSTALL_DIR/$CONFIG_FILE_NAME
				result=$?
				if [ $result -eq 0 ]
				then
					/mnt/mtd/gdclient_compro_startup.sh $1 &
					exit 0
				else
					sleep 5
				fi
			done
		else
			$LOGGER "ERROR: GDClient is not available" 
		fi
	done
	
	cd $current_dir
}

main $1 &
exit 0
