#!/bin/bash

set -e

function cleanup {
  set +e

  npm run kill_selenium

  echo "\nYou can safely ignore errors below, if you see any"

  # kill chrome driver
  CHROMEDRIVER_PID=`ps -ef | grep chromedriver | grep -v grep | awk '{print $2}'`
  if [ "$CHROMEDRIVER_PID" ] ; then
    kill -9 $CHROMEDRIVER_PID
  fi
  # kill test app
  APP_PID=`ps -ef | grep 'corsproxy' | grep -v grep | awk '{print $2}'`
  if [ "$APP_PID" ] ; then
    kill -9 $APP_PID
  fi
}

# always kill selenium, no matter if tests pass or exit
trap cleanup EXIT

if [ ! -d "/tmp/sv-selenium" ]; then
  echo 'Selenium not yet installed, downloading & installing ...'
  npm run install_selenium_and_chromedriver
fi

npm run start_selenium_with_chromedriver &
DEBUG=1 npm start &

COUNTER=0
until $(curl --output /dev/null --silent --head --fail http://localhost:1338); do
    let COUNTER=COUNTER+1
    echo "Waiting for app ... $COUNTER / 60"
    sleep 1
    if [[ COUNTER -eq 60 ]] ; then
      echo ""
      echo "App start timeout"
      exit 1
    fi
done
echo 'App started :)'

npm run test:mocha
