progName=serviceProgram
debugFileName=$progName"Debug.log"

if [ "$(uname --operating-system)" == "Msys" ]
then
    CFLAGS='-I.. -Wall -std=c++11 -DWIN32 -pthread -static -DDEBUG_LOG_FILE="'
    CFLAGS=$CFLAGS$(pwd)/$debugFileName\"
    CFLAGS='-I.. -Wall -std=c++11 -DWIN32 -pthread -static'
else
    CFLAGS='-I.. -Wall -std=c++11 -g -O0 -pthread -DDEBUG_LOG_FILE="'
    CFLAGS=$CFLAGS$(pwd)/$debugFileName\"
    CFLAGS='-I.. -Wall -std=c++11 -g -O0 -pthread'
fi

g++ $CFLAGS $progName.cpp ../CodeDweller/service.cpp -o $progName
if [ $? -ne 0 ]
then
    exit -1
fi

rm -f $debugFileName

# Function to run a test.
#
# Usage:
#
#   run_test <message>
#
run_test() {

    message=$1

    logFile=$progName$message.log

    rm -f $logFile

    if [ "$(uname --operating-system)" == "Msys" ]
    then

	sc create "Test Service" binPath= "$(pwd)/$progName.exe" > /dev/null 2>&1

	#echo "Starting at     "$(date +"%H:%M:%S.%N")
	sc start "Test Service" "$(pwd)/$logFile" $message > /dev/null 2>&1
	#echo "Sleeping 1 s at "$(date +"%H:%M:%S.%N")
	sleep 1

	#echo "Pausing at      "$(date +"%H:%M:%S.%N")
	sc pause "Test Service" > /dev/null 2>&1
	#echo "Sleeping 2 s at "$(date +"%H:%M:%S.%N")
	sleep 2

	#echo "Continuing at   "$(date +"%H:%M:%S.%N")
	sc continue "Test Service" > /dev/null 2>&1
	#echo "Sleeping 2 s at "$(date +"%H:%M:%S.%N")
	sleep 2

	#echo "Stopping at     "$(date +"%H:%M:%S.%N")
	sc stop "Test Service" > /dev/null 2>&1
	#echo "Returned at     "$(date +"%H:%M:%S.%N")
	sleep 1

	sc delete "Test Service" > /dev/null 2>&1

    else

	name=$(pwd)/$progName
	killall --exact --signal KILL --quiet $name
	sleep 1

	$name $(pwd)/$logFile $message
	sleep 1

	PID=$(pidof $name)

	kill -TSTP $PID

	if [ $message != "Pause" ]
	then
	    # In the Pause test, the service should have exited.
	    sleep 2
	    kill -CONT $PID

	    if [ $message != "Resume" ]
	    then
		# In the Resume test, the service should have exited.
		sleep 2
		kill -TERM $PID
	    fi
	fi

    # Wait for process to exit.
	exited=no
	for i in $(seq 10)
	do
	    if pidof $name > /dev/null 2>&1
	    then
		sleep 1
	    else
		exited=yes
		break
	    fi
	done

	if [ $exited == "no" ]
	then
	    echo CodeDweller::Service $message:  fail--$progName did not exit
	    return 1
	fi

    fi

    if diff --strip-trailing-cr expected_$logFile $logFile > /dev/null 2>&1
    then
	echo CodeDweller::Service $message:  ok
    else
	echo CodeDweller::Service $message:  fail
	return 1
    fi

return 0

}

# Run tests.
run_test Nominal
nominal_status=$?

# Stop timeout.
run_test Stop
stop_status=$?

if [ $nominal_status == "0" -a \
    $stop_status == "0" ]
then
    exit 0
fi
exit 1