#!/usr/bin/env bash
#
# install.sh — install (or remove) the macOS LaunchAgent that auto-starts the
# agent-queue run loop 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/agent-queue/.
#
set -euo pipefail

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

LABEL="com.bytelyst.agent-queue"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG_DIR="$HOME/Library/Logs/agent-queue"
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"
  echo "[launchd] (the run loop is stopped; queued jobs stay in queue/inbox/)"
}

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

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

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 restart if it ever exits non-zero (crash/reboot). -->
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <!-- Guard against tight crash loops. -->
    <key>ThrottleInterval</key>
    <integer>30</integer>

    <key>WorkingDirectory</key>
    <string>$AQ_DIR</string>

    <key>StandardOutPath</key>
    <string>$LOG_DIR/agent-queue.out.log</string>
    <key>StandardErrorPath</key>
    <string>$LOG_DIR/agent-queue.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>
        <key>AGENT_QUEUE_ENGINE</key>
        <string>codex</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"
echo "[launchd] status : launchctl print $DOMAIN/$LABEL | sed -n '1,20p'"
echo "[launchd] logs   : tail -f $LOG_DIR/agent-queue.out.log"
echo "[launchd] stop   : bash $SCRIPT_DIR/install.sh --uninstall"
echo
echo "Drop prompt .md files into: $AQ_DIR/queue/inbox/"
echo "Override engine/concurrency/secrets in ~/.agent-queue.env (e.g. AGENT_QUEUE_MAX=1)."
