#!/usr/bin/env bash
# install.sh — install or uninstall telemetry_monitor as a background service
#
# Linux:  systemd unit at /etc/systemd/system/telemetry_monitor.service
# macOS:  launchd agent at ~/Library/LaunchAgents/com.telemetry_monitor.plist
#
# Usage:
#   sudo ./install.sh                     (Linux — install service)
#   sudo ./install.sh --uninstall         (Linux — remove service)
#   ./install.sh                          (macOS — install service)
#   ./install.sh --uninstall              (macOS — remove service)

set -euo pipefail

INGEST_URL="${INGEST_URL:-https://aiyoo.in:4443/jeeves/ingest}"
INGEST_TOKEN="${INGEST_TOKEN:-secret-token}"
USER_EMAIL="${USER_EMAIL:-}"
SERVICE_NAME="telemetry_monitor"
INSTALL_BIN="/usr/local/bin/telemetry_monitor"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Parse optional arguments
UNINSTALL=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --uninstall|uninstall)
      UNINSTALL=1
      shift
      ;;
    --email|-e)
      USER_EMAIL="${2:-}"
      shift 2
      ;;
    --email=*)
      USER_EMAIL="${1#*=}"
      shift
      ;;
    *)
      shift
      ;;
  esac
done

# If INGEST_TOKEN is not in env or is secret-token, try to read from local .env if present
if [[ -f "$SCRIPT_DIR/.env" ]]; then
  ENV_TOK="$(grep -E '^INGEST_TOKEN=' "$SCRIPT_DIR/.env" | head -n1 | cut -d= -f2- | tr -d '\"' | tr -d "'" || true)"
  if [[ -n "$ENV_TOK" ]]; then
    INGEST_TOKEN="$ENV_TOK"
  fi
fi

# ── detect OS ──────────────────────────────────────────────────────────────────
OS="$(uname -s)"

# ── email validation helper ───────────────────────────────────────────────────
validate_email() {
  local em="$1"
  if [[ ${#em} -gt 254 || ${#em} -lt 3 ]]; then
    return 1
  fi
  if [[ "$em" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    return 0
  fi
  return 1
}

# ── handle uninstall ──────────────────────────────────────────────────────────
if [[ $UNINSTALL -eq 1 ]]; then
  echo "Uninstalling $SERVICE_NAME..."
  case "$OS" in
    Linux)
      systemctl stop "$SERVICE_NAME" 2>/dev/null || true
      systemctl disable "$SERVICE_NAME" 2>/dev/null || true
      rm -f /etc/systemd/system/telemetry_monitor.service /etc/systemd/system/sysmonitor.service
      systemctl daemon-reload
      rm -f "$INSTALL_BIN" /usr/local/bin/sysmonitor
      echo "✓ telemetry_monitor service and binary successfully removed."
      exit 0
      ;;
    Darwin)
      PLIST="$HOME/Library/LaunchAgents/com.telemetry_monitor.plist"
      OLD_PLIST="$HOME/Library/LaunchAgents/com.sysmonitor.plist"
      launchctl unload "$PLIST" 2>/dev/null || true
      launchctl unload "$OLD_PLIST" 2>/dev/null || true
      rm -f "$PLIST" "$OLD_PLIST"
      rm -f "$INSTALL_BIN" /usr/local/bin/sysmonitor
      echo "✓ telemetry_monitor launchd agent and binary successfully removed."
      exit 0
      ;;
    *)
      echo "ERROR: unsupported OS '$OS'." >&2
      exit 1
      ;;
  esac
fi

# ── prompt for email if interactive and not provided ───────────────────────────
if [[ -z "$USER_EMAIL" ]]; then
  if [[ -t 0 && -t 1 ]]; then
    echo "── Device Owner Configuration ─────────────────────────────────────────"
    echo "Enter primary user/owner email for this device"
    echo "(or press Enter to auto-detect via LDAP/SSSD/directory services):"
    read -r PROMPTED_EMAIL || true
    if [[ -n "${PROMPTED_EMAIL:-}" ]]; then
      if validate_email "$PROMPTED_EMAIL"; then
        USER_EMAIL="$PROMPTED_EMAIL"
        echo "✓ Registered initial owner: $USER_EMAIL"
      else
        echo "⚠ Invalid email format; continuing with automatic directory resolution."
      fi
    else
      echo "Continuing with automatic directory resolution."
    fi
    echo "────────────────────────────────────────────────────────────────────────"
  fi
fi

DOWNLOAD_BASE_URL="${DOWNLOAD_BASE_URL:-https://aiyoo-downloads.web.app}"

case "$OS" in
  Linux)
    if [[ -f "$SCRIPT_DIR/dist/telemetry_monitor-linux-amd64" ]]; then
      BINARY="$SCRIPT_DIR/dist/telemetry_monitor-linux-amd64"
    elif [[ -f "$SCRIPT_DIR/telemetry_monitor-linux-amd64" ]]; then
      BINARY="$SCRIPT_DIR/telemetry_monitor-linux-amd64"
    elif [[ -f "$SCRIPT_DIR/dist/sysmonitor-linux-amd64" ]]; then
      BINARY="$SCRIPT_DIR/dist/sysmonitor-linux-amd64"
    else
      echo "Binary not found locally. Downloading telemetry_monitor-linux-amd64 from $DOWNLOAD_BASE_URL..."
      TMP_BIN="$(mktemp /tmp/telemetry_monitor.XXXXXX)"
      curl -sSL "$DOWNLOAD_BASE_URL/telemetry_monitor-linux-amd64" -o "$TMP_BIN"
      chmod 755 "$TMP_BIN"
      BINARY="$TMP_BIN"
    fi

    echo "Installing telemetry_monitor (Linux / systemd)..."

    install -m 755 "$BINARY" "$INSTALL_BIN"
    echo "  binary  -> $INSTALL_BIN"

    UNIT_FILE="/etc/systemd/system/telemetry_monitor.service"
    EXTRA_FLAGS=""
    if [[ -n "$USER_EMAIL" ]]; then
      EXTRA_FLAGS=" -email $USER_EMAIL"
    fi
    cat > "$UNIT_FILE" <<EOF
[Unit]
Description=telemetry_monitor endpoint collector
After=network-online.target
Wants=network-online.target

[Service]
Environment="INGEST_URL=$INGEST_URL"
Environment="INGEST_TOKEN=$INGEST_TOKEN"
ExecStart=$INSTALL_BIN -ingest $INGEST_URL -no-local-storage$EXTRA_FLAGS
Restart=on-failure
RestartSec=15s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    chmod 600 "$UNIT_FILE"
    echo "  unit    -> $UNIT_FILE"

    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"
    systemctl restart "$SERVICE_NAME"
    echo ""
    echo "✓ telemetry_monitor service started."
    systemctl status "$SERVICE_NAME" --no-pager -l
    ;;

  Darwin)
    ARCH="$(uname -m)"

    if [[ "$ARCH" == "arm64" ]]; then
      BIN_NAME="telemetry_monitor-darwin-arm64"
    else
      BIN_NAME="telemetry_monitor-darwin-amd64"
    fi

    if [[ -f "$SCRIPT_DIR/dist/$BIN_NAME" ]]; then
      BINARY="$SCRIPT_DIR/dist/$BIN_NAME"
    elif [[ -f "$SCRIPT_DIR/$BIN_NAME" ]]; then
      BINARY="$SCRIPT_DIR/$BIN_NAME"
    else
      echo "Binary not found locally. Downloading $BIN_NAME from $DOWNLOAD_BASE_URL..."
      TMP_BIN="$(mktemp /tmp/telemetry_monitor.XXXXXX)"
      curl -sSL "$DOWNLOAD_BASE_URL/$BIN_NAME" -o "$TMP_BIN"
      chmod 755 "$TMP_BIN"
      BINARY="$TMP_BIN"
    fi

    PLIST="$HOME/Library/LaunchAgents/com.telemetry_monitor.plist"

    echo "Installing telemetry_monitor (macOS / launchd, arch=$ARCH)..."

    install -m 755 "$BINARY" "$INSTALL_BIN"
    EMAIL_PLIST_ARGS=""
    if [[ -n "$USER_EMAIL" ]]; then
      EMAIL_PLIST_ARGS="    <string>-email</string>
    <string>$USER_EMAIL</string>"
    fi

    mkdir -p "$HOME/Library/LaunchAgents"
    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>com.telemetry_monitor</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>INGEST_TOKEN</key>
    <string>$INGEST_TOKEN</string>
  </dict>
  <key>ProgramArguments</key>
  <array>
    <string>$INSTALL_BIN</string>
    <string>-ingest</string>
    <string>$INGEST_URL</string>
    <string>-no-local-storage</string>
$EMAIL_PLIST_ARGS
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$HOME/Library/Logs/telemetry_monitor.log</string>
  <key>StandardErrorPath</key>
  <string>$HOME/Library/Logs/telemetry_monitor.log</string>
</dict>
</plist>
EOF
    echo "  plist   -> $PLIST"

    launchctl load "$PLIST"
    echo ""
    echo "✓ Service loaded. Check status:"
    echo "  launchctl list | grep telemetry_monitor"
    ;;

  *)
    echo "ERROR: unsupported OS '$OS'. Use install.ps1 on Windows." >&2
    exit 1
    ;;
esac

echo ""
echo "telemetry_monitor is configured to send to: $INGEST_URL"
echo "To monitor live logs:"
echo "  journalctl -u telemetry_monitor -f"
