#!/usr/bin/env bash

set -eu


export HOME=$(mktemp -d)
export ATUIN_CONFIG_DIR=$HOME/.config/atuin

server_url=http://localhost:8888
server_log=$HOME/atuin-server.log
server_pid=

cleanup() {
	test_status=$?
	trap - EXIT HUP INT TERM

	if [ -n $server_pid ]; then
		kill $server_pid 2>/dev/null || true
		wait $server_pid 2>/dev/null || true
	fi

	if [ $test_status -ne 0 ]; then
		echo '[test] atuin server log'
		cat $server_log >&2 || true
	fi

	exit $test_status
}

trap cleanup EXIT
trap 'exit 1' HUP INT TERM

mkdir -p $ATUIN_CONFIG_DIR

cp debian/tests/server.toml debian/tests/config.toml $ATUIN_CONFIG_DIR/
sed -i'' s:@DBDIR@:$HOME: $ATUIN_CONFIG_DIR/server.toml

atuin-server start >$server_log 2>&1 &
server_pid=$!

echo '[test] waiting for atuin-server to be ready'

attempt=0
until curl -fsS "$server_url/healthz" >/dev/null 2<&1; do
	if ! kill -0 $server_pid 2>/dev/null; then
		if wait $server_pid; then
			server_status=0
		else
			server_status=$?
		fi
		server_pid=
		echo "[test] atuin-server exited before ready: status $server_status" >&2
		exit 1
	fi

	attempt=$((attempt + 1))
	if [ "$attempt" -ge 10 ]; then
		echo '[test] timed out waiting for atuin-server' >&2
		exit 1
	fi
	sleep 1
done

echo '[test] ping health endpoint'

curl -fsS "$server_url/healthz"

echo # response body has no newline and curl won't fill in

echo '[test] client registration'

atuin account register --username test --email test@example.invalid --password test

echo '[test] client re-login'

key=$(atuin key)

atuin logout

atuin login --username test --password test --key "$key"

echo '[test] client sync'

atuin sync

### cleanup

kill $server_pid
