#!/usr/bin/env bash
#
# HostSeba NOC — Probe location installer
#
# Run on each remote monitoring node (Singapore, US, Europe, BD, etc.) to
# turn it into a probe that checks targets and pushes results to the NOC.
#
# Usage:
#   curl -fsSL https://noc.hostseba.com/probe/install.sh | sudo bash -s -- \
#     --code sg-aws-1 \
#     --secret noc_probe_xxxxxxxxxxxx \
#     --backend https://noc.hostseba.com
#
# What it does:
#   1. Creates dedicated unprivileged user `hostseba-probe`
#   2. Installs probe.sh to /opt/hostseba-probe/
#   3. Installs systemd unit (with strict resource limits)
#   4. Starts the probe — it begins polling /probe/targets every 5 minutes
#      and pushing results to /probe/results
#
# Safety: probe is read-only just like the agent. It never modifies any
# target system or this host's configuration beyond its own install dir.

set -euo pipefail

# Defaults (the install URL gets these rewritten by the backend at serve time)
BACKEND_URL="${BACKEND_URL:-https://noc.hostseba.com}"
INSTALL_DIR="/opt/hostseba-probe"
CONFIG_DIR="/etc/hostseba-probe"
LOG_DIR="/var/log/hostseba-probe"
PROBE_USER="hostseba-probe"
CODE=""
SECRET=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --code)    CODE="$2"; shift 2 ;;
    --secret)  SECRET="$2"; shift 2 ;;
    --backend) BACKEND_URL="$2"; shift 2 ;;
    --help|-h) sed -n '2,25p' "$0"; exit 0 ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
done

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
say()  { printf "${CYAN}[probe]${NC} %s\n" "$*"; }
ok()   { printf "${GREEN}[ok]${NC} %s\n" "$*"; }
warn() { printf "${YELLOW}[warn]${NC} %s\n" "$*"; }
die()  { printf "${RED}[err]${NC} %s\n" "$*" >&2; exit 1; }

[[ $EUID -eq 0 ]] || die "Run as root: sudo bash probe-install.sh ..."
[[ -n "$CODE" ]] || die "--code is required (get it from NOC dashboard → Probe Locations → Add)"
[[ -n "$SECRET" ]] || die "--secret is required"

# --- User ---
if ! id "$PROBE_USER" &>/dev/null; then
  say "Creating user $PROBE_USER..."
  useradd --system --no-create-home --shell /sbin/nologin "$PROBE_USER" || true
fi

# --- Dirs ---
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$LOG_DIR"
chown "$PROBE_USER:$PROBE_USER" "$LOG_DIR"
chmod 755 "$INSTALL_DIR" "$CONFIG_DIR"
chmod 750 "$LOG_DIR"

# --- Verify credentials ---
say "Verifying credentials with $BACKEND_URL..."
status=$(curl -fsSL -o /dev/null -w "%{http_code}" \
  --connect-timeout 10 --max-time 15 \
  -H "X-Probe-Code: $CODE" \
  -H "X-Probe-Secret: $SECRET" \
  "$BACKEND_URL/api/probe/heartbeat" 2>/dev/null) || status="000"

if [[ "$status" != "200" ]]; then
  die "Heartbeat failed (HTTP $status). Check --code, --secret, and --backend, then retry."
fi
ok "Credentials accepted by NOC"

# --- Config ---
cat > "$CONFIG_DIR/probe.conf" <<EOF
# HostSeba NOC Probe — config (auto-generated)
PROBE_CODE=$CODE
PROBE_SECRET=$SECRET
BACKEND_URL=$BACKEND_URL
TARGETS_REFRESH_SECONDS=300
PUSH_BATCH_SIZE=50
EOF
chmod 640 "$CONFIG_DIR/probe.conf"
chown root:"$PROBE_USER" "$CONFIG_DIR/probe.conf"
ok "Config written to $CONFIG_DIR/probe.conf"

# --- Download probe.sh ---
say "Downloading probe..."
curl -fsSL --connect-timeout 10 --max-time 30 \
  -o "$INSTALL_DIR/probe.sh" \
  "$BACKEND_URL/probe/probe.sh" || die "Could not download probe.sh"
chmod 755 "$INSTALL_DIR/probe.sh"
ok "Probe installed at $INSTALL_DIR/probe.sh"

# --- systemd ---
if command -v systemctl >/dev/null 2>&1; then
  say "Installing systemd unit..."
  cat > /etc/systemd/system/hostseba-probe.service <<EOF
[Unit]
Description=HostSeba NOC monitoring probe
Documentation=$BACKEND_URL/docs/probe
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$PROBE_USER
Group=$PROBE_USER
EnvironmentFile=$CONFIG_DIR/probe.conf
ExecStart=$INSTALL_DIR/probe.sh
Restart=on-failure
RestartSec=15s
StartLimitBurst=5
StartLimitIntervalSec=300

# Resource limits — same posture as the agent
CPUQuota=10%
MemoryMax=128M
MemoryHigh=96M
IOSchedulingClass=idle
IOSchedulingPriority=7
Nice=15
TasksMax=30

# Security hardening
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=$LOG_DIR
ReadOnlyPaths=$CONFIG_DIR
NoNewPrivileges=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources

StandardOutput=append:$LOG_DIR/probe.log
StandardError=append:$LOG_DIR/probe.log

[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable --now hostseba-probe.service
  ok "Probe service started — see logs: journalctl -u hostseba-probe -f"
else
  warn "systemd not detected — set up a cron yourself: */1 * * * * $INSTALL_DIR/probe.sh --once"
fi

cat <<EOF

----
Probe '$CODE' is now active. It will:
  1. Poll the NOC for monitored targets every 5 minutes
  2. Run the configured checks (HTTP/TCP/ICMP) against each
  3. Push results to $BACKEND_URL/api/probe/results

Status:    sudo systemctl status hostseba-probe
Logs:      sudo journalctl -u hostseba-probe -f
Stop:      sudo systemctl stop hostseba-probe
Uninstall: sudo systemctl disable --now hostseba-probe; sudo rm -rf $INSTALL_DIR $CONFIG_DIR $LOG_DIR
----

EOF
