#!/usr/bin/sh

set -eou pipefail

scenario_name="$1"
project_root="$(dirname $(cargo locate-project | jq -r .root))"
scenario_dir="$project_root/tests/hurl_integration/$1"
scenario_tmp_dir_path="$project_root/tmp/tests/$scenario_name"
database_path="$project_root/tmp/tests/$scenario_name/minauthator.db"

echo "Starting scenario $scenario_name."
mkdir -p $scenario_tmp_dir_path
if [ -f $database_path ]; then
    rm $database_path
fi
sqlite3 $database_path < $project_root/migrations/all.sql

export DB_PATH=$database_path
if [ -f $scenario_dir/init_db.sh ]; then
    $scenario_dir/init_db.sh
fi

pkill -f $project_root/target/debug/minauthator-server &
sleep 0.1
$project_root/target/debug/minauthator-server \
    --config "$scenario_dir/config.toml" \
    --database  $database_path \
    --listen-host "127.0.0.1" \
    --listen-port "8086" \
    --static-assets "$project_root/assets" &

server_pid=$!
sleep 0.2
hurl \
    --variable base_url="http://localhost:8086" \
    --test --error-format long \
    $scenario_dir/main.hurl
kill $server_pid
echo "End of scenario."