#!/usr/bin/env bash
# ARP Guardian sensor — one-line installer for Ubuntu / Debian.
#
# Usage (run as root):
#   curl -fsSL https://arpguardian.meirlan.ru/install-sensor.sh \
#     | sudo bash -s -- --controller http://YOUR-CONTROLLER:8080 --token TOKEN
#
# Or, if you already scp'd this script in:
#   sudo bash install-sensor.sh --controller http://YOUR-CONTROLLER:8080 --token TOKEN
#
# What it does:
#   1. Verifies root + Ubuntu/Debian
#   2. Installs curl + libcap2-bin if missing
#   3. Downloads the latest sensor binary from the public landing site
#      (https://arpguardian.meirlan.ru/downloads/arpg-sensor-linux-x64) —
#      no enrollment token required for the download itself.
#   4. Runs `arpg-sensor enroll` against the controller (writes
#      /etc/arpg/sensor.toml, installs systemd unit with auto-restart,
#      starts the service).
#   5. Runs a 15-second coverage check so the operator immediately knows
#      whether this sensor will see enough traffic for full detection.
#
# Safe to re-run: enroll is idempotent at the controller (UPSERT on sensor_id)
# but each call consumes one enrollment token. Generate a fresh one for re-runs.

set -euo pipefail

CONTROLLER=""
TOKEN=""
INSECURE=""
BINARY_URL="${ARPG_BINARY_URL:-https://arpguardian.meirlan.ru/downloads/arpg-sensor-linux-x64}"

while [ $# -gt 0 ]; do
    case "$1" in
        --controller)              CONTROLLER="$2";    shift 2 ;;
        --token)                   TOKEN="$2";         shift 2 ;;
        --binary-url)              BINARY_URL="$2";    shift 2 ;;
        --insecure-skip-tls-verify|-k) INSECURE="-k";  shift 1 ;;
        -h|--help)
            sed -n '3,28p' "$0"
            exit 0
            ;;
        *) echo "unknown flag: $1"; exit 2 ;;
    esac
done

if [ -z "$CONTROLLER" ] || [ -z "$TOKEN" ]; then
    echo "error: --controller and --token are required"
    echo "       generate the token in the dashboard (Sensors → Generate token)"
    exit 2
fi

if [ "$(id -u)" -ne 0 ]; then
    echo "error: install-sensor.sh must be run as root (use sudo)"
    exit 1
fi

if [ ! -f /etc/os-release ]; then
    echo "error: /etc/os-release missing — only Ubuntu/Debian are supported"
    exit 1
fi
. /etc/os-release
case "$ID ${ID_LIKE:-}" in
    *ubuntu*|*debian*) ;;
    *) echo "warning: only Ubuntu/Debian are officially supported; ID=$ID. Continuing anyway." ;;
esac

echo "[install] target: $ID $VERSION_ID"

# 1. curl
if ! command -v curl >/dev/null 2>&1; then
    echo "[install] curl missing — installing via apt..."
    apt-get update -qq && apt-get install -y -qq curl
fi
# 2. libcap2-bin for setcap
if ! command -v setcap >/dev/null 2>&1; then
    echo "[install] setcap missing — installing libcap2-bin..."
    apt-get install -y -qq libcap2-bin
fi

# 3. Download binary from the public landing site (no auth required).
BIN_PATH="/usr/local/bin/arpg-sensor"
TMP_BIN="$(mktemp)"
echo "[install] downloading sensor binary from $BINARY_URL ..."
curl -fsSL "$BINARY_URL" -o "$TMP_BIN"
chmod 0755 "$TMP_BIN"
install -m 0755 "$TMP_BIN" "$BIN_PATH"
rm -f "$TMP_BIN"
echo "[install] binary installed at $BIN_PATH ($(stat -c %s "$BIN_PATH") bytes)"

# 4. Enroll (writes config, sets caps, installs systemd unit with auto-restart, starts)
echo "[install] running enroll..."
"$BIN_PATH" enroll --controller "$CONTROLLER" --token "$TOKEN" $INSECURE

# 5. Coverage check
echo
echo "[install] running 15s coverage check ..."
IFACE_GUESS=$(awk -F'=' '/^iface/ {gsub(/[ "]/, "", $2); print $2; exit}' /etc/arpg/sensor.toml 2>/dev/null || echo ens33)
set +e
"$BIN_PATH" doctor --coverage 15 -i "$IFACE_GUESS"
COV_EXIT=$?
set -e
case "$COV_EXIT" in
    0) echo "[install] ✅ Coverage check: FULL — all detection rules will be active." ;;
    1) echo "[install] ⚠️  Coverage check: PARTIAL — own + bcast only. Unicast rules degraded.
                See https://arpguardian.meirlan.ru/docs/sensor-coverage.html for SPAN / vSwitch promisc setup." ;;
    2) echo "[install] ⚠️  Coverage check: BROADCAST-ONLY — switched ethernet without mirroring.
                Detection will only fire on broadcast-shaped attacks.
                See https://arpguardian.meirlan.ru/docs/sensor-coverage.html." ;;
    3) echo "[install] ❌ Coverage check: SILENT — no traffic captured. Investigate
                interface state and VLAN wiring before relying on detection." ;;
    *) echo "[install] coverage check returned exit=$COV_EXIT (non-standard)" ;;
esac
echo
echo "[install] Done. UI: $CONTROLLER  →  Sensors page (this sensor should appear in ~10s)."
echo "          Auto-restart: systemctl status arpg-sensor"
