#!/usr/bin/env bash
# RuntimeGuard agent installer
# Usage: curl -sSL https://install.runtimeguard.io | sudo bash
set -euo pipefail

DOWNLOAD_BASE="https://install.runtimeguard.io/releases"
INSTALL_DIR="/usr/local/bin"
BINARY="runtimeguard-agent"
SERVICE_NAME="runtimeguard"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

# ── Helpers ────────────────────────────────────────────────────────────────────
log()  { echo "  → $*"; }
ok()   { echo "  ✓ $*"; }
die()  { echo "✗ ERROR: $*" >&2; exit 1; }

# ── Root check ─────────────────────────────────────────────────────────────────
[[ $EUID -eq 0 ]] || die "Run as root: curl -sSL https://install.runtimeguard.io | sudo bash"

# ── OS / arch check ────────────────────────────────────────────────────────────
OS=$(uname -s)
ARCH=$(uname -m)
[[ "$OS" == "Linux" ]] || die "RuntimeGuard requires Linux"

case "$ARCH" in
  x86_64)  ARCH_SUFFIX="amd64" ;;
  aarch64) ARCH_SUFFIX="arm64" ;;
  *)       die "Unsupported architecture: $ARCH (need x86_64 or aarch64)" ;;
esac

# ── eBPF / BTF detectie ────────────────────────────────────────────────────────
# CO-RE vereist dat de kernel BTF informatie exporteert via /sys/kernel/btf/vmlinux.
# Dit is beschikbaar vanaf kernel 5.2+ en is standaard ingeschakeld op:
#   Ubuntu 20.04+, Debian 11+, RHEL 8+, Amazon Linux 2023, Fedora 31+, etc.
KERNEL=$(uname -r)
USE_EBPF=false
VARIANT_SUFFIX=""

if [[ -f /sys/kernel/btf/vmlinux ]]; then
  USE_EBPF=true
  VARIANT_SUFFIX="-ebpf"
  log "BTF found (/sys/kernel/btf/vmlinux) — using eBPF mode"
else
  echo ""
  echo "  ⚠  Kernel $KERNEL has no BTF (/sys/kernel/btf/vmlinux not found)."
  echo "     RuntimeGuard will use inotify/proc monitoring (requires kernel ≥ 3.5)."
  echo "     For eBPF mode: use kernel 5.2+ with BTF enabled."
  echo ""
fi

DOWNLOAD_URL="${DOWNLOAD_BASE}/runtimeguard-agent-linux-${ARCH_SUFFIX}${VARIANT_SUFFIX}"

# ── Download ───────────────────────────────────────────────────────────────────
TMP=$(mktemp)
trap "rm -f $TMP" EXIT
log "Downloading runtimeguard-agent (linux/${ARCH_SUFFIX})..."
curl -fsSL -o "$TMP" "$DOWNLOAD_URL"
chmod +x "$TMP"
mv "$TMP" "${INSTALL_DIR}/${BINARY}"
ok "Installed to ${INSTALL_DIR}/${BINARY}"

# ── systemd unit ──────────────────────────────────────────────────────────────
if command -v systemctl &>/dev/null; then
  # Schrijf environment variabelen in de service als ze meegegeven zijn
  ENV_LINES=""
  if [[ -n "${AGENT_API_KEY:-}" ]]; then
    ENV_LINES="${ENV_LINES}Environment=AGENT_API_KEY=${AGENT_API_KEY}\n"
  fi
  ENV_LINES="${ENV_LINES}Environment=AGENT_HOST_ID=${AGENT_HOST_ID:-$(hostname)}\n"
  ENV_LINES="${ENV_LINES}Environment=AGENT_BACKEND_URL=${AGENT_BACKEND_URL:-https://api.runtimeguard.io}\n"

  cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=RuntimeGuard agent
Documentation=https://runtimeguard.io/get-started
After=network-online.target
Wants=network-online.target

[Service]
$(printf "%b" "$ENV_LINES")ExecStart=${INSTALL_DIR}/${BINARY}
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  ok "Systemd unit installed: ${SERVICE_FILE}"
else
  log "systemd not found — skipping service installation"
fi

# ── Done ───────────────────────────────────────────────────────────────────────
echo ""
echo "  ✓ RuntimeGuard agent installed successfully"
echo ""

if [[ -n "${AGENT_API_KEY:-}" ]]; then
  echo "  Enable and start the agent:"
  echo ""
  echo "       sudo systemctl enable --now ${SERVICE_NAME}"
  echo ""
  echo "  Check status:"
  echo ""
  echo "       sudo journalctl -u ${SERVICE_NAME} -f"
else
  echo "  Next steps:"
  echo "  1. Set your API key:"
  echo ""
  echo "       sudo systemctl edit ${SERVICE_NAME}"
  echo ""
  echo "     Add:"
  echo "       [Service]"
  echo "       Environment=AGENT_API_KEY=your_key_here"
  echo "       Environment=AGENT_HOST_ID=\$(hostname)"
  echo ""
  echo "  2. Enable and start the agent:"
  echo ""
  echo "       sudo systemctl enable --now ${SERVICE_NAME}"
fi
echo ""
