#!/bin/bash

set -e
set -m

function run_selftest() {
  rm -rf tmp
  cargo run -- --selftest --force  --silent tmp
  cd tmp
  node_modules/.bin/tap test.js
  cd ..
}

function run_esm_selftest() {
  rm -rf tmp
  cargo run -- --selftest --esm --force  --silent tmp
  cd tmp
  node test.js
  cd ..
}

function run_startup() {
  rm -rf tmp
  cargo run -- tmp --force --silent

  echo 'running the server'
  PORT=8080 tmp/boltzmann.js --startup &

  sleep 2 # ha ha ha ha ha
  echo 'attempting to curl'
  result=$(curl -sL http://127.0.0.1:8080/hello/world)

  echo 'stopping the server'
  kill %1
  wait

  if [ "$result" != "hello world" ]; then
    echo -e "expected \"hello world\", got \"$result\""
    exit 1
  fi
  rm -rf tmp
}

function run_examples() {
  for example in examples/*; do
    if [ "$example" = "examples/sessions" ]; then
      continue
    fi

    pushd $example
    cargo run -- . --force --silent --githubci=off

    echo "testing $example startup"
    PORT=8080 ./boltzmann.js &
    kill %1
    wait

    echo "testing $example startup"
    npm t # this may trigger docker-compose up

    if [ -e ./docker-compose.yml ]; then
      docker-compose down || echo 'no docker detected'
    fi

    popd
    git checkout $example
    git clean -f -q $example
  done
}

function list_tests() {
  typeset -f          | \
    grep '()'         | \
    grep 'run_*'      | \
    grep -v 'run_all' | \
    awk '{print $1}'  | \
    sort              | \
    sed -e 's/run_//g'
}

function run_all() {
  for test in $(list_tests); do
    run_$test
  done
}

case $1 in
  "selftest")
    run_selftest
  ;;
  "startup")
    run_startup
  ;;
  "examples")
    run_examples
  ;;
  "list")
    list_tests
  ;;
  *)
    run_all
  ;;
esac
