# receive parameters:
# $1 (store|receive)
# $2 IP
# $3 ID
# $4 Flag
#
# Returns:
# 0: remote malfunction, service not up, answer garbled, other remote failures
# 1: service up, no flag  (not used for 'store')
# 2: success
# 3: internal error/local failure 


export DISPLAY=:1.0

if [ $# -lt 4 ] ; then
        echo "script called with f** bad parameters"
        exit 3
fi

wget -O /dev/null -t 1 $2:8180/Hoverboard -o /home/gameserver/robofox/realms/hovtest$2/status
TEMP=`grep saved /home/gameserver/robofox/realms/hovtest$2/status | wc -l`
rm /home/gameserver/robofox/realms/hovtest$2/status
if [ "$TEMP" == "0" ] ; then
	exit 0
fi

WorkDir=$(pwd)/Checkers/hoverboard

NS=`date +%N`
TEMP=`echo "$NS % 3" | bc`
if [ "$TEMP" == "0" ] ; then
	DOM="@fbiclub.xxx"
elif [ "$TEMP" == "1" ] ; then
	DOM="@dukat.eu"
else
	DOM="@ally.co"
fi

FN=`/var/www/da.op3n/gameserver/id2text --name $3`
LN=`/var/www/da.op3n/gameserver/id2text --familyname $3`
UN=`/var/www/da.op3n/gameserver/id2text --login $3`
PW=`echo $4 | cut -b1-9`
EM=`echo $4$DOM`
IP=$2

if [ "$1" == "store" ] ; then
	TEMP=`echo "$3 % 2" | bc`

        cp -r /home/gameserver/robofox/realms/hovtest/* /home/gameserver/robofox/realms/hovtest$2

	if [ "$TEMP" == "0" ] ; then

		/home/gameserver/robofox/bin/robofox hovtest$2 $WorkDir/hovcheck-AccS.txt @@IP@@ $IP @@UN@@ $UN @@EM@@ $EM @@FN@@ $FN @@LN@@ $LN @@PW@@ $PW

	else

		EM=`echo $4 | cut -b2-6`
		EM=`echo $EM$DOM`
		CT=$4

		/home/gameserver/robofox/bin/robofox hovtest$2 $WorkDir/hovcheck-BloS.txt @@IP@@ $IP @@UN@@ $UN @@EM@@ $EM @@FN@@ $FN @@LN@@ $LN @@PW@@ $PW @@CT@@ $CT
	fi

	/home/gameserver/robofox/bin/robofox hovtest $WorkDir/hovcheck-Read.txt @@IP@@ $IP @@UN@@ $UN @@PW@@ $PW

        exit 2

elif [ "$1" == "retrieve" ] ; then
        TEMP=`echo "$3 % 2" | bc`
        if [ "$TEMP" == "0" ] ; then

	        /home/gameserver/robofox/bin/robofox hovtest$2 $WorkDir/hovcheck-AccR.txt @@IP@@ $IP @@UN@@ $UN @@PW@@ $PW > /home/gameserver/robofox/realms/hovtest$2/HVDUMP
		TEMP=`grep "<td>$4" /home/gameserver/robofox/realms/hovtest$2/HVDUMP | wc -l`
		TEMP2=`grep "<td> $4" /home/gameserver/robofox/realms/hovtest$2/HVDUMP | wc -l`
		rm /home/gameserver/robofox/realms/hovtest$2/HVDUMP
	        if [ "$TEMP" == "0" -a "$TEMP2" == "0" ] ; then
        		exit 1
	        else
			exit 2
		fi

	else
		/home/gameserver/robofox/bin/robofox hovtest$2 $WorkDir/hovcheck-BloR.txt @@IP@@ $IP @@UN@@ $UN @@PW@@ $PW > /home/gameserver/robofox/realms/hovtest$2/HVDUMP
                TEMP=`grep "<p>$4" /home/gameserver/robofox/realms/hovtest$2/HVDUMP | wc -l`
                TEMP2=`grep "<p> $4" /home/gameserver/robofox/realms/hovtest$2/HVDUMP | wc -l`
		rm /home/gameserver/robofox/realms/hovtest$2/HVDUMP
                if [ "$TEMP" == "0" -a "$TEMP2" == "0" ] ; then
                        exit 1
                else
                        exit 2
                fi

 	fi

else
        echo "script called with unknown operation"
        exit 3
fi  
