#!/bin/sh
set -e

xvfb-run -a sh -c '
    kiwix-desktop 2>/tmp/kiwix-desktop-startup.log &
    APP_PID=$!

    # Wait for the QtSingleApplication lockfile to appear in /tmp.
    # QtLocalPeer creates this file in the KiwixApp constructor, before
    # init() is called, making it the earliest reliable startup indicator
    # that does not depend on X11 window properties or _NET_WM_PID.
    # The file is named: qtsingleapp-kiwixd-<crc16hex>-<uid>-lockfile
    STARTED=0
    for i in $(seq 60); do
        if ! kill -0 "$APP_PID" 2>/dev/null; then
            echo "FAIL: kiwix-desktop crashed during startup" >&2
            cat /tmp/kiwix-desktop-startup.log >&2
            exit 1
        fi
        ls /tmp/qtsingleapp-kiwixd-*-lockfile 2>/dev/null | grep -q . && STARTED=1 && break
        sleep 1
    done
    if [ "$STARTED" -eq 0 ]; then
        kill -KILL "$APP_PID" 2>/dev/null || true
        echo "FAIL: kiwix-desktop did not complete startup within 60 seconds" >&2
        cat /tmp/kiwix-desktop-startup.log >&2
        exit 1
    fi

    # Brief stability check: confirm the process has not crashed right after startup.
    sleep 2
    if ! kill -0 "$APP_PID" 2>/dev/null; then
        echo "FAIL: kiwix-desktop exited unexpectedly after startup" >&2
        cat /tmp/kiwix-desktop-startup.log >&2
        exit 1
    fi

    # SIGKILL avoids two problems that SIGTERM and WM_DELETE_WINDOW have:
    # - SIGTERM: default handler calls _exit(), causing QThreadStorage warnings.
    # - WM_DELETE_WINDOW: triggers the Downloader destructor which blocks
    #   indefinitely waiting for aria2c to stop.
    kill -KILL "$APP_PID" 2>/dev/null || true
'
