#!/bin/bash
set -e

cd "${0%/*}/.."

DIST_JS='dist/aftr.js'

NODE_ENV="test"

function log {
  echo
  echo "--- $@"
}

if [ -f .storage.env ]; then
  log "sourcing .storage.env"
  source .storage.env
fi

if ! [ -f "$DIST_JS" ]; then
  echo "run 'yarn run build' first."
  exit 1
fi

log "installing integration test dependencies..."
cp "$DIST_JS" test/app/aftr.js
# https://github.com/yarnpkg/yarn/issues/5419
yarn
mv node_modules node_modules_dev
yarn --production --frozen-lockfile
rm -rf test/app/node_modules
mv node_modules test/app/node_modules
mv node_modules_dev node_modules

log "starting func server..."
cd test/app
func start > func.log &

log "running tests..."
cd ..
babel-node index.js || export TEST_EXIT_CODE="$?"

log "killing func server..."
kill -9 $(ps | grep -E "dotnet|node" | tr -s ' ' | cut -d ' ' -f 2)

if [ -n "$TEST_EXIT_CODE" ]; then
  exit "$TEST_EXIT_CODE"
fi
