#!/usr/bin/env bash
# gstack-ios-qa-daemon — Mac-side daemon that brokers tailnet/loopback traffic
# to a connected iPhone running the in-app StateServer over the CoreDevice USB
# tunnel. Single-instance via flock on ~/.gstack/ios-qa-daemon.pid.
#
# Usage:
#   gstack-ios-qa-daemon                         # loopback-only (local USB)
#   gstack-ios-qa-daemon --tailnet               # additionally open tailnet listener
#
# Environment:
#   GSTACK_IOS_DAEMON_PORT       — loopback listener port (default 9099)
#   GSTACK_IOS_TARGET_UDID       — target iOS device UDID (optional; otherwise
#                                  the first paired connected device is used)
#   GSTACK_IOS_TARGET_BUNDLE_ID  — bundle ID of the iOS app hosting StateServer
#                                  (default com.gstack.iosqa.fixture)
#
# Readiness protocol: prints `READY: port=<n> pid=<pid>` to stdout once both
# listeners are bound. Spawners read stdin with a ~5s timeout to confirm.
#
# Exits cleanly when no active loopback clients are connected AND no remote
# session tokens are outstanding.

set -euo pipefail
# The --help heredoc is over 512 bytes; keep it off a pipe (test/heredoc-pipe-deadlock.test.ts).
BASH_COMPAT=50

case "${1:-}" in
  -h|--help)
    cat <<'EOF'
Usage:
  gstack-ios-qa-daemon [--tailnet]
  gstack-ios-qa-daemon --help

Mac-side broker for /ios-qa and /ios-design-review. By default it binds a
loopback listener for a USB-connected iPhone running the in-app StateServer.
Pass --tailnet to also open the Tailscale listener after the local tailscaled
identity probe succeeds.

Options:
  --tailnet   Enable the authenticated tailnet listener in addition to loopback.
  -h, --help  Print this help and exit without starting the daemon.

Environment:
  GSTACK_IOS_DAEMON_PORT       Loopback listener port. Default: 9099.
  GSTACK_IOS_TARGET_UDID       Target iOS device UDID. Optional.
  GSTACK_IOS_TARGET_BUNDLE_ID  Bundle ID hosting StateServer. Default: com.gstack.iosqa.fixture.

Readiness:
  The daemon prints "READY: port=<n> pid=<pid>" once the listener is bound.
  Probe local health with: curl -sf http://127.0.0.1:${GSTACK_IOS_DAEMON_PORT:-9099}/healthz
EOF
    exit 0
    ;;
esac

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GSTACK_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
ENTRY="$GSTACK_DIR/ios-qa/daemon/src/index.ts"

if [ ! -f "$ENTRY" ]; then
  echo "gstack-ios-qa-daemon: missing $ENTRY (gstack install incomplete?)" >&2
  exit 1
fi

if ! command -v bun >/dev/null 2>&1; then
  echo "gstack-ios-qa-daemon: bun runtime not on PATH — install from https://bun.sh" >&2
  exit 1
fi

exec bun run "$ENTRY" "$@"
