#!/usr/bin/env bash
# AppRun entry point for the poreFlow Linux AppImage.
#
# Executed by the AppImage runtime when the .AppImage is run. Mirrors the
# terminal-relaunch behaviour of start-poreflow.sh (the zip/macOS launcher): a
# double-clicked binary has no controlling terminal, so the user would never see
# the "Serving at localhost:..." URL nor be able to Ctrl+C to stop the waitress
# server (closing the browser tab does NOT stop it).
#
# AppImage-specific twist: the squashfs is mounted only while THIS AppRun
# process is alive. So we must not exec a terminal emulator that forks-and-exits
# (e.g. gnome-terminal's default server mode) -- that returns immediately, the
# AppImage unmounts, and the app's files vanish mid-run. We therefore use each
# emulator's BLOCKING flag (gnome-terminal --wait, konsole --nofork,
# xfce4-terminal --disable-server; xterm is foreground already) so the exec'd
# emulator stays as the AppRun process until its window closes.
set -euo pipefail

HERE="$(dirname "$(readlink -f "$0")")"
BIN="$HERE/usr/lib/poreflow/poreflow"

# Hidden smoke/CLI passthrough: run the frozen binary directly, no terminal
# window and no "Press Enter" pause. Used by CI's frozen smoke test (which runs
# `<appimage> --appimage-extract-and-run smoke <fast5>` non-interactively).
if [ "${1:-}" = "smoke" ]; then
    exec "$BIN" "$@"
fi

run_app() {
    echo "poreFlow is starting - keep this window open."
    echo "Press Ctrl+C here, or close this window, to quit."
    echo
    set +e
    "$BIN" "$@"
    local status=$?
    set -e
    echo
    echo "poreFlow has stopped (exit ${status}). Press Enter to close."
    read -r _ || true
    exit "${status}"
}

# Already attached to a terminal (run from a shell, or relaunched by us below):
# just run the app here. The env guard prevents an infinite relaunch loop if an
# emulator never provides a tty.
if [ -t 1 ] || [ "${POREFLOW_IN_TERMINAL:-}" = "1" ]; then
    run_app "$@"
fi

export POREFLOW_IN_TERMINAL=1
SELF="$HERE/AppRun"

# Relaunch inside the first available terminal emulator, using its blocking
# flag so the AppImage stays mounted for the app's lifetime (see header).
for term in gnome-terminal konsole xfce4-terminal xterm; do
    command -v "$term" >/dev/null 2>&1 || continue
    case "$term" in
        gnome-terminal) exec "$term" --wait --title=poreFlow -- bash "$SELF" "$@" ;;
        konsole)        exec "$term" --nofork -e bash "$SELF" "$@" ;;
        xfce4-terminal) exec "$term" --disable-server --title=poreFlow -x bash "$SELF" "$@" ;;
        xterm)          exec "$term" -title poreFlow -e bash "$SELF" "$@" ;;
    esac
done

# No terminal emulator found: run headless. The server still works; the user
# just has no console. Better than exiting silently.
run_app "$@"
