#!/bin/sh
set -e

# fd 4 traces commands. fd 3 is reserved below for the server's FIFO stdin.
exec 4>&2
run() { echo "+ $*" >&4; "$@"; }

# Start the local web UI and confirm it actually serves something.
# start_ui() returns as soon as the listener is up (and tries to open a
# browser, which fails harmlessly with no display, see allow-stderr),
# so the server process must be kept alive separately via a FIFO on its
# stdin, same as the quack test.
tmp="${AUTOPKGTEST_TMP:-$(mktemp -d)}"

fifo="$tmp/ui.fifo"
rm -f "$fifo"
mkfifo "$fifo"

echo "+ duckdb -cmd ... CALL start_ui(); (background, logs to $tmp/server.log)" >&4
duckdb -cmd "LOAD ui; CALL start_ui();" \
  < "$fifo" > "$tmp/server.log" 2>&1 4>&- &
server_pid=$!
cleanup() {
    exec 3>&- 2>/dev/null || true
    kill "$server_pid" 2>/dev/null || true
    rm -f "$fifo"
    [ -z "${AUTOPKGTEST_TMP:-}" ] && rm -rf "$tmp"
    true
}
trap cleanup EXIT

exec 3>"$fifo"
sleep 2

run curl -sf -o /dev/null http://localhost:4213/
