#!/bin/bash
# Applotus Sentinel agent installer for macOS.
#
# Installs the agent under ~/.applotus and registers a LaunchAgent so it starts at login and is
# restarted if it exits. Re-running is safe: it replaces what it installed before.
#
# A LaunchAgent rather than a LaunchDaemon on purpose. A daemon starts at boot without a login,
# which sounds better, but it runs outside any GUI session and so cannot capture the screen --
# the in-browser desktop would stop working. If this Mac must come up unattended after a reboot
# with nobody logging in, enable automatic login for this user, or move the plist to
# /Library/LaunchDaemons and accept that the desktop feature will not work.
set -u

SERVER_URL="https://applotus.fly.dev"
TENANT_ID="tenant_default"
API_KEY=""
LABEL="com.applotus.sentinel-agent"
INSTALL_DIR="$HOME/.applotus"
AGENT_PATH="$INSTALL_DIR/sentinel-agent.py"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG="$HOME/Library/Logs/applotus-sentinel.log"

echo "[1/5] Locating a working python3..."
# Fixed absolute paths, not `command -v python3`: on a Mac without Command Line Tools the PATH
# python3 is a stub that opens an install dialog, and launchd cannot answer one -- with KeepAlive
# it would respawn forever. Each candidate is executed to prove it actually runs.
PY=""
for cand in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3; do
  if [ -x "$cand" ] && "$cand" -c "import sys" >/dev/null 2>&1; then PY="$cand"; break; fi
done
if [ -z "$PY" ]; then
  echo "  ERROR: no working python3 found."
  echo "  Run: xcode-select --install   (or: brew install python3)   then re-run this script."
  exit 1
fi
echo "  Using $PY"

echo "[2/5] Downloading the agent..."
mkdir -p "$INSTALL_DIR" "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"
if ! curl -fsSL "$SERVER_URL/download/sentinel-agent.py" -o "$AGENT_PATH"; then
  echo "  ERROR: could not download the agent from $SERVER_URL"
  exit 1
fi
# A truncated download would install cleanly and then crash on every launch, so check it parses.
if ! "$PY" -m py_compile "$AGENT_PATH" >/dev/null 2>&1; then
  echo "  ERROR: the downloaded agent did not compile -- the download was probably truncated."
  exit 1
fi
echo "  Installed $AGENT_PATH"

echo "[3/5] Writing the LaunchAgent..."
# Written by this script rather than pasted, which is the entire point: each <string> goes on
# its own line and nothing depends on a long line surviving a terminal paste.
{
  printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>'
  printf '%s\n' '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'
  printf '%s\n' '<plist version="1.0">' '<dict>'
  printf '  <key>Label</key><string>%s</string>\n' "$LABEL"
  printf '%s\n' '  <key>ProgramArguments</key>' '  <array>'
  printf '    <string>%s</string>\n' "$PY"
  printf '    <string>%s</string>\n' "$AGENT_PATH"
  printf '    <string>%s</string>\n' "--server"
  printf '    <string>%s</string>\n' "$SERVER_URL"
  printf '    <string>%s</string>\n' "--tenant"
  printf '    <string>%s</string>\n' "$TENANT_ID"
  printf '%s\n' '  </array>'
  printf '%s\n' '  <key>RunAtLoad</key><true/>' '  <key>KeepAlive</key><true/>'
  printf '  <key>StandardOutPath</key><string>%s</string>\n' "$LOG"
  printf '  <key>StandardErrorPath</key><string>%s</string>\n' "$LOG"
  printf '%s\n' '</dict>' '</plist>'
} > "$PLIST"
if ! plutil -lint "$PLIST" >/dev/null 2>&1; then
  echo "  ERROR: the generated plist is not valid. Leaving it at $PLIST for inspection."
  exit 1
fi
echo "  Wrote $PLIST"

echo "[4/5] Loading it..."
# unload first so re-running replaces a previous install instead of erroring on a duplicate label.
launchctl unload "$PLIST" >/dev/null 2>&1
if ! launchctl load -w "$PLIST" >/dev/null 2>&1; then
  echo "  ERROR: launchctl load failed. See $LOG"
  exit 1
fi

echo "[5/5] Checking it started..."
sleep 3
if launchctl list | grep -q "$LABEL"; then
  echo "  Running."
else
  echo "  WARNING: not listed by launchctl yet. Check $LOG"
fi

echo ""
echo "================================================"
echo " Done. The agent starts at login and restarts"
echo " if it exits."
echo ""
echo " Logs:   tail -f $LOG"
echo " Stop:   launchctl unload $PLIST"
echo " Remove: launchctl unload $PLIST && rm $PLIST"
echo "================================================"
