#!/bin/bash
echo hello
# turn off echo
set +v
# list all arguments
echo "$@" >./log.txt

#initialize variables 
ipadress="127.0.0.1"
port="8080"
expectedresult="Success"


# initialize the options with their values 
while [ "$#" -gt 0 ]; do
  case "$1" in
    -ipadress) ipadress="$2"; shift 2;;
    -port) port="$2"; shift 2;;
    -expectedresult) expectedresult="$2"; shift 2;;

    --ipadress=*) ipadress="${1#*=}"; shift 1;;
    --port=*) port="${1#*=}"; shift 1;;
    --expectedresult=*) expectedresult="${1#*=}"; shift 1;;

    -*) echo "unhandled  option: $1" >&2 ; shift 1;;
    --*) echo "unhandled option: $1" >&2 ; shift 1;;
	
	*) args+="$1"; shift 1;;
  esac
done

# Enumerating arguments but we don't use them in that script
for arg
do
    echo $arg >>./log.txt
done

# To get the value of a single parameter, just remember to include the `-`
echo The value of ipadress is: $ipadress  >>./log.txt
echo The value of port is: $port  >>./log.txt
echo The value of expectedresult is: $expectedresult  >>./log.txt




curl http://$ipadress:$port/xstudio/api?command=getInfo >./curlresult.txt
curlError=$?
echo >>./log.txt
echo Curl returned error  $curlError >>./log.txt


# assertion if string is found the server asnwers something good to te request
grep "application_title"  curlresult.txt >/dev/null
grepError=$?
echo >>./log.txt
echo gred returned error  $grepError >>./log.txt
cat ./curlresult.txt >>./log.txt
rm ./curlresult.txt


# see if you got a success
errorcode=0
if [ $grepError -eq 0 ] && [ $curlError -eq 0 ]
then
	echo "[Success] Server answered" >> ./log.txt
	# if we expected a failure then this not good
	if [ "$expectedresult" = "Failure" ]
	then 
		echo "[Failure] we expected a $expectedresult" >>./log.txt
		errorcode=1
	# otherwise this is as expected
	elif [ "$expectedresult" = "Success" ]
	then
		echo "[Success] we expected a $expectedresult" >>./log.txt
		errorcode=0
	fi
# you got a failure ...	
else
	echo "[Failure] Didn't get answer back" >>./log.txt
	if [ "$expectedresult" = "Failure" ]
	then 
		echo "[Success] we expected a $expectedresult" >>./log.txt
		errorcode=0
	elif [ "$expectedresult" = "Success" ]
	then
		echo "[Failure] we expected a $expectedresult" >>./log.txt
		errorcode=2
	fi
fi

# handle errorcode 
exit $errorcode	







