#!/usr/bin/env bash
#
# install.sh — install (or remove) the macOS LaunchAgent that auto-starts
# tracker-web (the fleet web tracker, :3003) on login and keeps it alive across
# reboot/crash.
#
#   bash launchd/install.sh             # render plist, load, and start now
#   bash launchd/install.sh --uninstall # stop, unload, and remove the plist
#
# The plist is generated from the resolved repo path so it works on any clone.
# Logs land in ~/Library/Logs/tracker-web/.
#
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
WEB_DIR="$(cd -- "$SCRIPT_DIR/.." >/dev/null 2>&1 && pwd -P)"
WRAPPER="$SCRIPT_DIR/tracker-web-boot.sh"

LABEL="com.bytelyst.tracker-web"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG_DIR="$HOME/Library/Logs/tracker-web"
UID_NUM="$(id -u)"
DOMAIN="gui/$UID_NUM"

if [ "$(uname -s)" != "Darwin" ]; then
  echo "install.sh: macOS only (LaunchAgents). On Linux use a systemd --user unit." >&2
  exit 1
fi

uninstall() {
  echo "[launchd] booting out $LABEL ..."
  launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
  rm -f "$PLIST"
  echo "[launchd] removed $PLIST (tracker-web stopped)"
}

if [ "${1:-}" = "--uninstall" ] || [ "${1:-}" = "-u" ]; then
  uninstall
  exit 0
fi

[ -f "$WRAPPER" ] || { echo "install.sh: missing $WRAPPER" >&2; exit 1; }
chmod +x "$WRAPPER" 2>/dev/null || true
mkdir -p "$HOME/Library/LaunchAgents" "$LOG_DIR"

# Avoid a port clash: if something else is already serving :3003 (e.g. a
# deploy-gigafactory.sh --tracker-only run), stop it so launchd owns the port.
if lsof -ti tcp:3003 >/dev/null 2>&1; then
  echo "[launchd] freeing :3003 (an existing tracker is running) ..."
  lsof -ti tcp:3003 | xargs kill 2>/dev/null || true
  sleep 2
fi

echo "[launchd] writing $PLIST"
cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$LABEL</string>

    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>$WRAPPER</string>
    </array>

    <!-- Start on login and ALWAYS restart it if it exits, for any reason
         (crash, reboot, OOM, or a clean SIGTERM that exits 0 — a long-lived web
         server should never just stay down). -->
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <!-- Guard against tight crash loops. -->
    <key>ThrottleInterval</key>
    <integer>10</integer>

    <key>WorkingDirectory</key>
    <string>$WEB_DIR</string>

    <key>StandardOutPath</key>
    <string>$LOG_DIR/tracker-web.out.log</string>
    <key>StandardErrorPath</key>
    <string>$LOG_DIR/tracker-web.err.log</string>

    <!-- launchd's PATH is minimal; the wrapper also repairs PATH defensively. -->
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
</dict>
</plist>
EOF

# Reload cleanly (bootout first so a re-run picks up plist changes).
launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
launchctl bootstrap "$DOMAIN" "$PLIST"
launchctl enable "$DOMAIN/$LABEL"
launchctl kickstart -k "$DOMAIN/$LABEL"

echo "[launchd] installed + started: $LABEL  (http://localhost:3003)"
echo "[launchd] status : launchctl print $DOMAIN/$LABEL | sed -n '1,20p'"
echo "[launchd] logs   : tail -f $LOG_DIR/tracker-web.out.log"
echo "[launchd] stop   : bash $SCRIPT_DIR/install.sh --uninstall"
echo
echo "NOTE: while this LaunchAgent owns :3003, do NOT also run"
echo "      deploy-gigafactory.sh --with-tracker (it would clash on the port)."
