#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NODE_BIN="${NODE_BIN:-/opt/homebrew/opt/node@24/bin/node}"
PLIST="$HOME/Library/LaunchAgents/cn.tkmind.goosed-monitor.plist"
LOG="$HOME/Library/Logs/goosed-monitor.log"
GUI="gui/$(id -u)"

mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"

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>cn.tkmind.goosed-monitor</string>
  <key>ProgramArguments</key>
  <array>
    <string>$NODE_BIN</string>
    <string>$ROOT/scripts/monitor-goosed-fds.mjs</string>
  </array>
  <key>WorkingDirectory</key>
  <string>$ROOT</string>
  <key>StartInterval</key>
  <integer>60</integer>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$LOG</string>
  <key>StandardErrorPath</key>
  <string>$LOG</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/opt/homebrew/bin:/opt/homebrew/opt/node@24/bin:/usr/local/bin:/usr/bin:/bin</string>
    <key>GOOSED_FD_WARN</key>
    <string>180</string>
    <key>GOOSED_FD_RESTART</key>
    <string>3200</string>
    <key>SANDBOX_MCP_MAX_TOTAL</key>
    <string>80</string>
    <key>SANDBOX_MCP_MAX_PER_ROOT</key>
    <string>2</string>
  </dict>
</dict>
</plist>
EOF

plutil -lint "$PLIST"
launchctl bootout "$GUI/cn.tkmind.goosed-monitor" 2>/dev/null || true
launchctl bootstrap "$GUI" "$PLIST"
launchctl enable "$GUI/cn.tkmind.goosed-monitor"
launchctl kickstart -k "$GUI/cn.tkmind.goosed-monitor"

echo "installed $PLIST"
echo "log: $LOG"
