#!/usr/bin/env bash
# ReplyPilot Portal Agent installer for Linux (systemd user service, no root needed).
# Usage: bash install-linux.sh [--token TOKEN] [--api URL] | --uninstall
set -euo pipefail
PORTAL_API="https://app.replypilot.ca/api/agent"; TOKEN="${RP_ENROLL_TOKEN:-}"
DIR="${XDG_DATA_HOME:-$HOME/.local/share}/replypilot-agent"
UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"

if [ "${1:-}" = "--uninstall" ]; then
  systemctl --user disable --now replypilot-agent.service 2>/dev/null || true
  rm -f "$UNIT_DIR/replypilot-agent.service"; rm -rf "$DIR"
  systemctl --user daemon-reload 2>/dev/null || true
  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

command -v curl >/dev/null || { echo "curl is required. Install it with your package manager and retry." >&2; exit 1; }
command -v systemctl >/dev/null || { echo "systemd is required for the background service." >&2; exit 1; }
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" "$UNIT_DIR"
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 > "$UNIT_DIR/replypilot-agent.service" <<UNIT
[Unit]
Description=ReplyPilot Portal Agent
After=network-online.target

[Service]
ExecStart=/usr/bin/env bash $DIR/agent.sh
Restart=always
RestartSec=15

[Install]
WantedBy=default.target
UNIT
systemctl --user daemon-reload
systemctl --user enable --now replypilot-agent.service
command -v loginctl >/dev/null && loginctl enable-linger "$USER" 2>/dev/null || true
echo "ReplyPilot Portal Agent installed and running."
echo "Status:  systemctl --user status replypilot-agent"
echo "Remove:  bash $0 --uninstall"
