#!/usr/bin/env bash
# ReplyPilot Portal Agent installer for macOS (launchd user agent, no admin needed).
# Usage: bash install-macos.sh [--token TOKEN] [--api URL] | --uninstall
set -euo pipefail
PORTAL_API="https://app.replypilot.ca/api/agent"; TOKEN="${RP_ENROLL_TOKEN:-}"
DIR="$HOME/Library/Application Support/ReplyPilot Agent"
LABEL="ca.replypilot.agent"; PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"

if [ "${1:-}" = "--uninstall" ]; then
  launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
  rm -f "$PLIST"; rm -rf "$DIR"
  echo "ReplyPilot Portal Agent removed."; exit 0
fi
while [ $# -gt 0 ]; do case "$1" in
  --token) TOKEN="$2"; shift 2;; --api) PORTAL_API="$2"; shift 2;; *) echo "Unknown option: $1" >&2; exit 2;; esac; done

if [ -z "$TOKEN" ]; then read -r -p "Enrollment token (from your portal account): " TOKEN </dev/tty; fi
[ -n "$TOKEN" ] || { echo "An enrollment token is required." >&2; exit 1; }

mkdir -p "$DIR" "$HOME/Library/LaunchAgents"
cat > "$DIR/agent.sh" <<'AGENT_EOF'
#!/usr/bin/env bash
# ReplyPilot Portal Agent (macOS / Linux). Dependency-free: needs bash + curl.
# Reads config.env, sends a heartbeat to the portal every INTERVAL seconds.
set -u
AGENT_VERSION="1.0.0"
CONF="${RP_AGENT_CONF:-$(cd "$(dirname "$0")" && pwd)/config.env}"
# shellcheck disable=SC1090
. "$CONF"
INTERVAL="${INTERVAL:-60}"

json_escape() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\n\r\t'; }
host="$(json_escape "$(hostname)")"
os="$(uname -s)"; arch="$(uname -m)"

log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*"; }

enroll() {
  [ -n "${ENROLL_TOKEN:-}" ] || { log "no enrollment token configured"; return 1; }
  local body resp
  body="{\"token\":\"$(json_escape "$ENROLL_TOKEN")\",\"hostname\":\"$host\",\"os\":\"$os\",\"arch\":\"$arch\",\"agent_version\":\"$AGENT_VERSION\"}"
  resp="$(curl -fsS --max-time 20 -H 'Content-Type: application/json' -d "$body" "$PORTAL_API/enroll")" || return 1
  DEVICE_ID="$(printf '%s' "$resp" | sed -n 's/.*"device_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
  DEVICE_SECRET="$(printf '%s' "$resp" | sed -n 's/.*"device_secret"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
  [ -n "$DEVICE_ID" ] && [ -n "$DEVICE_SECRET" ] || return 1
  # Persist credentials and drop the one-time token.
  umask 077
  { grep -v -E '^(ENROLL_TOKEN|DEVICE_ID|DEVICE_SECRET)=' "$CONF"; \
    printf 'DEVICE_ID=%q\nDEVICE_SECRET=%q\n' "$DEVICE_ID" "$DEVICE_SECRET"; } > "$CONF.new" && mv "$CONF.new" "$CONF"
  log "enrolled as $DEVICE_ID"
}

heartbeat() {
  curl -fsS --max-time 20 -o /dev/null -H 'Content-Type: application/json' \
    -H "Authorization: Bearer $DEVICE_SECRET" \
    -d "{\"device_id\":\"$DEVICE_ID\",\"hostname\":\"$host\",\"agent_version\":\"$AGENT_VERSION\"}" \
    "$PORTAL_API/heartbeat"
}

while true; do
  if [ -z "${DEVICE_SECRET:-}" ]; then
    if enroll; then . "$CONF"; else log "enrollment failed; retrying"; fi
  elif ! heartbeat; then
    log "heartbeat failed; will retry"
  fi
  sleep "$INTERVAL"
done
AGENT_EOF
chmod 700 "$DIR/agent.sh"
umask 077
printf 'PORTAL_API=%q\nENROLL_TOKEN=%q\nINTERVAL=60\n' "$PORTAL_API" "$TOKEN" > "$DIR/config.env"

cat > "$PLIST" <<PLISTEOF
<?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>$DIR/agent.sh</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>$DIR/agent.log</string>
  <key>StandardErrorPath</key><string>$DIR/agent.log</string>
</dict></plist>
PLISTEOF
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
echo "ReplyPilot Portal Agent installed and running."
echo "Log:     $DIR/agent.log"
echo "Remove:  bash $0 --uninstall"
