#!/bin/sh
# Smoke test for the installed package: make sure the GTK frontend can be
# imported (all GObject typelibs present) and that the headless daemon
# starts and accepts connections.
# Generated by DeepSeek V4.1 Flash via Debian Inference
set -eu

export PYTHONPATH="/usr/share${PYTHONPATH:+:$PYTHONPATH}"

python3 - <<'PY'
import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, Gtk  # noqa: F401

import hosty.daemon.server  # noqa: F401
import hosty.gtk_ui.application  # noqa: F401
import hosty.shared.backend.server_manager  # noqa: F401

print("hosty: installed modules import successfully")
PY

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

export HOME="$tmpdir"
export XDG_DATA_HOME="$tmpdir/.local/share"

port=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()')

/usr/bin/hosty --headless --host 127.0.0.1 --port "$port" >"$tmpdir/daemon.log" 2>&1 &
pid=$!
trap 'kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; rm -rf "$tmpdir"' EXIT

i=0
while ! python3 -c "import socket, sys; socket.create_connection(('127.0.0.1', int(sys.argv[1])), 1).close()" "$port" 2>/dev/null; do
    i=$((i + 1))
    if [ "$i" -ge 30 ]; then
        echo "hosty: headless daemon failed to start" >&2
        cat "$tmpdir/daemon.log" >&2
        exit 1
    fi
    sleep 1
done

echo "hosty: headless daemon accepted connections on 127.0.0.1:$port"
