#!/bin/bash
# Install CTM + Wall-E as a macOS Launch Agent so it starts automatically on login
# and auto-restarts on crash (but NOT on clean exit).
# Usage: bash bin/install-service.sh [--uninstall]

set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
LABEL="com.walle.server"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
PORT="${CTM_PORT:-3456}"

if [[ "$1" == "--uninstall" ]]; then
  launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || \
    launchctl unload "$PLIST" 2>/dev/null || true
  rm -f "$PLIST"
  echo "CTM service uninstalled."
  exit 0
fi

# Source .env for port and data dir overrides
ENV_VARS=""
if [[ -f "$ROOT/.env" ]]; then
  while IFS='' read -r line || [[ -n "$line" ]]; do
    [[ -z "$line" || "$line" == \#* ]] && continue
    key="${line%%=*}"
    value="${line#*=}"
    key=$(echo "$key" | xargs)
    value=$(echo "$value" | xargs | sed 's/^["'"'"']//;s/["'"'"']$//')
    [[ -z "$key" ]] && continue
    case "$key" in
      CTM_PORT) PORT="$value" ;;
    esac
    # XML-escape for plist safety
    esc_key=$(echo "$key" | sed 's/&/\&amp;/g;s/</\&lt;/g;s/>/\&gt;/g')
    esc_val=$(echo "$value" | sed 's/&/\&amp;/g;s/</\&lt;/g;s/>/\&gt;/g')
    ENV_VARS="$ENV_VARS
    <key>$esc_key</key>
    <string>$esc_val</string>"
  done < "$ROOT/.env"
fi

NODE=$(which node)
NODE_BIN_DIR=$(dirname "$NODE")
LOG_DIR="$HOME/.walle/logs"
mkdir -p "$LOG_DIR"

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>$NODE</string>
    <string>$ROOT/claude-task-manager/server.js</string>
  </array>
  <key>WorkingDirectory</key>
  <string>$ROOT</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>$NODE_BIN_DIR:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>
    <key>HOME</key>
    <string>$HOME</string>
    <key>CTM_PORT</key>
    <string>$PORT</string>
    <key>CTM_MANAGED_BY_LAUNCHD</key>
    <string>1</string>$ENV_VARS
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <dict>
    <key>SuccessfulExit</key>
    <false/>
  </dict>
  <key>ThrottleInterval</key>
  <integer>5</integer>
  <key>StandardOutPath</key>
  <string>$LOG_DIR/ctm.log</string>
  <key>StandardErrorPath</key>
  <string>$LOG_DIR/ctm.err</string>
</dict>
</plist>
EOF

# Load the service (unload first if previously loaded, wait for clean exit)
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || \
  launchctl unload "$PLIST" 2>/dev/null || true
sleep 1  # Let old process release port before bootstrapping new one
launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null || \
  launchctl load "$PLIST"

echo "CTM installed as a macOS Launch Agent."
echo ""
echo "  Status:    launchctl list $LABEL"
echo "  Logs:      tail -f ~/.walle/logs/ctm.log"
echo "  Errors:    tail -f ~/.walle/logs/ctm.err"
echo "  Dashboard: http://localhost:$PORT"
echo "  Uninstall: bash bin/install-service.sh --uninstall"
echo ""
echo "  Auto-restarts on crash. Clean exit (SIGTERM/SIGINT) stops the service."
echo "  To manually stop: launchctl kill SIGTERM gui/$(id -u)/$LABEL"
