#!/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; "$@"; }

# Server/client round trip over quack's own wire protocol. quack_serve()
# returns as soon as the listener is up, so the server process must be
# kept alive separately. A FIFO on its stdin does that without leaving
# any helper process behind.
tmp="${AUTOPKGTEST_TMP:-$(mktemp -d)}"

port=28391
fifo="$tmp/quack.fifo"
rm -f "$fifo"
mkfifo "$fifo"

echo "+ duckdb -cmd ... CALL quack_serve(...) (background, logs to $tmp/server.log)" >&4
duckdb -cmd "LOAD httpfs; LOAD quack;
  CREATE TABLE hello AS FROM VALUES ('world') v(s);
  CALL quack_serve('quack:localhost:$port', token => 'testtoken');" \
  < "$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

result=$(run duckdb -c "LOAD quack;
  ATTACH 'quack:localhost:$port' AS remote (TYPE quack, TOKEN 'testtoken', DISABLE_SSL true);
  FROM remote.hello;")
echo "$result" | grep -q "world"
