#!/usr/bin/env bash

mkdir -p cypress/log
LOGFILE=$(pwd)/cypress/log/integration-test.log
rm -f $LOGFILE
touch $LOGFILE

function info() {
  echo -e "\e[34;1m$1\e[0m"
}

function waitForStatusOk() {
  TRIES=10

  while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' $1)" != "200" ]]
  do
    if [[ "$TRIES" -lt 2 ]]
    then
      echo "failed to start $1"
      exit 1
    fi

    sleep 1
    let TRIES-=1
  done
}

info "starting frontend"
kill $(lsof -t -i:3010) > /dev/null 2>&1
PORT=3010 BACKEND_PORT=5010 npm --prefix ../frontend start > $LOGFILE 2>&1 &
FRONTEND_PROCESS=$!

info "starting fake csv provider"
kill $(lsof -t -i:5020) > /dev/null 2>&1
pushd ../backend > /dev/null 2>&1
  source env/bin/activate
  PORT=5020 python -m fakecsvprovider > $LOGFILE 2>&1 &
popd > /dev/null 2>&1
FAKE_CSV_PROCESS=$!

waitForStatusOk localhost:5020
info "fake csv provider started"

info "starting backend"
kill $(lsof -t -i:5010) > /dev/null 2>&1
pushd ../backend > /dev/null 2>&1
  source env/bin/activate
  source .env
  PORT=5010 CSV_LOCATION='http://localhost:5020/fixture.csv' python -m matchpredictor > $LOGFILE 2>&1 &
popd > /dev/null 2>&1
BACKEND_PROCESS=$!

waitForStatusOk localhost:3010
info "frontend started"

waitForStatusOk localhost:5010
info "backend started"

info "starting tests"
if [ "$KEEP_OPEN" = "true" ]
then
  npm start
else
  npm test
  TEST_RESULT=$?
fi

info "stopping frontend"
kill $FRONTEND_PROCESS

info "stopping backend"
kill $BACKEND_PROCESS

info "stopping fake csv provider"
kill $FAKE_CSV_PROCESS

info "complete!"

echo
if [ "$KEEP_OPEN" = "true" ]
then
    echo -e "[ \e[34;1mFINISHED\e[0m ]"
elif [ $TEST_RESULT -eq 0 ]
then
    echo -e "[ \e[32;1mSUCCESS\e[0m ]"
else
    echo -e "[ \e[31;1mFAILURE\e[0m ]"
fi
echo

exit $TEST_RESULT
