#!/bin/bash

echo "---------------------"
echo "Starting test server"

pushd ../../../../dev > /dev/null
vagrant ssh -c "/srv/comt/src/cm/scripts/test-suite/start-testserver.sh"
popd > /dev/null

SERVER_IP=`grep WORKSPACE_URL workspace.info.full.js | tail -n -1 | cut -d: -f2 | tr -d " //"`
SERVER_PORT=`grep WORKSPACE_URL ./workspace.info.full.js | tail -n -1 | cut -d: -f3 | tr -d " ');"`

if [[ -x `which nc` ]]; then
    SERVER_TEST_CMD="nc -z $SERVER_IP $SERVER_PORT"
elif [[ -x `which curl` ]]; then
    SERVER_TEST_CMD="curl --output /dev/null --silent --head --fail http://$SERVER_IP:$SERVER_PORT"
elif [[ -x `which wget` ]]; then
    SERVER_TEST_CMD="wget -q --spider http://$SERVER_IP:$SERVER_PORT"
fi
echo "$SERVER_TEST_CMD"

echo "---------------------"
if [[ -z "$SERVER_TEST_CMD" ]]; then
    echo "Waiting 10 seconds to let test server start"
    sleep 10
else
    for i in {1..10}; do
        echo "waiting 5 seconds to let the test server $SERVER_IP:$SERVER_PORT start"
        sleep 5
	if $SERVER_TEST_CMD; then
            break
        fi
    done
    if [ $i -eq 10 ]; then
         echo "could not start test server $SERVER_IP:$SERVER_PORT"
         exit 1
    fi
fi

echo "---------------------"
echo "Starting karma tests"
. ./start-test-suite.sh ./karma.conf.full.js $@

echo "---------------------"
echo "stopping test server + output test server logs"

pushd ../../../../dev > /dev/null
vagrant ssh -c "/srv/comt/src/cm/scripts/test-suite/clean-testserver.sh"
popd /dev/null


