#!/usr/bin/env bash
#
# agent-queue-boot.sh — boot/login entrypoint for the agent-queue run loop.
#
# Launched by the macOS LaunchAgent (see launchd/) so the folder-kanban worker
# auto-starts on login AND survives reboot/crash (LaunchAgent KeepAlive). This is
# the reboot-persistence layer that tmux + caffeinate alone cannot provide.
#
# It does three things launchd's minimal environment needs:
#   1. Repairs PATH so the agent CLIs (codex/devin/claude) + caffeinate are found.
#   2. Loads optional overrides from ~/.agent-queue.env.
#   3. Wraps `agent-queue run` in caffeinate (macOS) so the Mac won't sleep while
#      a job is running. NOTE: because the run loop is long-lived, this keeps the
#      machine awake for as long as the LaunchAgent runs — intended for a dedicated
#      overnight runner. Set AGENT_QUEUE_NO_CAFFEINATE=1 to allow idle sleep.
#
set -uo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"

# launchd hands processes a bare PATH — prepend the usual CLI install locations
# (Homebrew arm64/intel, ~/.local/bin for devin, system dirs) ahead of it.
export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH:-}"

# Optional per-machine overrides (engine, concurrency, tokens, NETWORK, etc.).
# This file is NOT tracked — keep secrets/host-specific config here.
if [ -f "$HOME/.agent-queue.env" ]; then
  # shellcheck disable=SC1091
  . "$HOME/.agent-queue.env"
fi

# Recommended default for a local monorepo overnight runner (see long-running-jobs
# cheat sheet): codex runs in-repo so @bytelyst/* workspace links resolve locally.
: "${AGENT_QUEUE_ENGINE:=codex}"
export AGENT_QUEUE_ENGINE

echo "[agent-queue-boot] $(date '+%Y-%m-%d %H:%M:%S') starting run loop" \
     "(engine=$AGENT_QUEUE_ENGINE, max=${AGENT_QUEUE_MAX:-3})"

# Keep the Mac awake for the lifetime of the loop unless explicitly opted out.
keep=""
if [ "${AGENT_QUEUE_NO_CAFFEINATE:-0}" != "1" ] && command -v caffeinate >/dev/null 2>&1; then
  keep="caffeinate -dimsu"
fi

# exec so the LaunchAgent tracks the real worker PID (clean KeepAlive restarts).
# shellcheck disable=SC2086
exec $keep "$SCRIPT_DIR/agent-queue.sh" run
