#!/usr/bin/env bash

# You can start me with $0 test1,test2,..
# or pointing to a file with one test per line

export TZ="Europe/Berlin"
G="\e[1;38;5;154m"
R="\e[1;38;5;124m"
O="\e[0m"
if [ "x$1" == "xno_cleanup" ]; then
    # the kill procedure did hang on travis, so we set this in .travis.yml:
    # on your CI server you do NOT want to set this,
    # xfvb and firefox will continue running otherwise:
    no_cleanup=1
    shift
fi
if [ "x$1" == "xkill" ]; then
    # handy when running this on the local machine
    for i in "" "-9"; do
        killall $i firefox
        killall $i python2
    done
    shift
    sleep 1
fi

set -x

export here=$(unset CDPATH && cd "$(dirname "$BASH_SOURCE")" && echo $PWD)

port="$TEST_PORT"
test ! -z $port || port=8080



if [ "x$1" == "xprepare" ]; then

    if [ ! -e /usr/bin/nodejs ]
    then
        sudo ln -s /usr/bin/node /usr/bin/nodejs 2>/dev/null
    fi
    # python version will be detected by test_server, resulting in
    # different run_transcrypt
    python --version
    python3 --version
    python3.5 --version
    python3.6 --version
    python3.7 --version
    java -version
    echo "node version: `nodejs --version`"
    echo 'prepare ready'
    echo '--------------'
    echo 'INFO'
    cat "$here/README.md"
    exit 0
fi

tests="$1"
test ! -z "$tests" || { echo -e "$R no tests $O"; exit 1; }

stop_flag="/tmp/transcrypt_tester_stopflag_$port"
rm -f "$stop_flag"
export DISPLAY=:99.0
url="http://127.0.0.1:$port/do/$tests"

echo "Testurl is: $url"
# Launch XVFB detached from this process
# If we don't detach - then the PGID will not be
# different from the 'run' script
setsid /usr/bin/xvfb-run -a firefox "$url" &
if [ $? -ne 0 ]
then
    echo "$R Failed to Launch XVFB/Firefox: $? $O"
    exit 3
fi

# Get the PID of xvfb-run (parent process)
XVFB_PID=$(ps -e -o pid,cmd | \
           grep "[x]vfb-run -a firefox" | \
           head -n 1 | \
           grep -o -m 1 "\([[:digit:]]*\) ")

# Get the Process Group ID for xvfb-run, the parent of a
# group of process that run under it
XVFB_PGID=$(ps -o pgid= $XVFB_PID | grep -o "[[:digit:]]*")

# Kill the XVFB process group and all children
function killXVFB() {
    # @note - xvfb-run generates child processes which
    #   means you can't just kill xvfb-run - you gotta
    #   kill the group
    echo "Killing XVFB PID=$XVFB_PID PGID=$XVFB_PGID"
    kill -- -$XVFB_PGID
}


echo "Testserver port is: $port"
python2 "$here/test_server.py" $port &
if [ $? -ne 0 ]
then
    echo "$R Failed to launch test server: $? $O"
    killXVFB
    exit 3
fi

TESTSERVER_PID=$!

# This function is called to correctly kill
# the children processes started by this script
function killChildren() {
    killXVFB
    echo "Killing TESTSERVER PID=$TESTSERVER_PID"
    kill $TESTSERVER_PID
}

# Control-C Handler Function
function ctrlCTrap() {
    echo "**** Control-C ****"
    killChildren
    exit 2
}

# Capture the Ctrl-C input so that we can correctly
# kill children in the middle of a run.
trap ctrlCTrap INT

echo 'polling now for stopfile'
ERR_FOUND=1

set +x
while true; do
    sleep 1
    if [ -e "$stop_flag" ]; then
        cat "$stop_flag" | grep "ERR" && {
            echo -e "$R stopflag with status ERR found $O"
            break
        } || {
            echo -e "$G all well $O"
            ERR_FOUND=0
            break
        }
    fi
    # echo '.' # no output, to make travis end it earlier on endless loops, ie.
    # when result never comes....
done

test "x$no_cleanup" = "x" && killChildren \
    || echo 'Not killing children, $no_cleanup is set'

echo "Error Status: $ERR_FOUND"
exit $ERR_FOUND

#echo -e "$R No stopflag found $O"
#exit 1
