#!/usr/bin/env sh
# Nebula agent installer — https://nebula.crazyde.de
set -e

TOKEN=""
PORT="9101"
AGENT_URL="https://nebula.crazyde.de/api/agent"
REPORT_URL="https://nebula.crazyde.de/api/agent/report"
INSTALL_DIR="/opt/nebula-agent"

while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

echo "==> Nebula agent installer"

# --- Root check ---
if [ "$(id -u)" -ne 0 ]; then
  echo "This installer needs root. Re-run with sudo." >&2
  exit 1
fi

# --- Node.js check ---
if ! command -v node >/dev/null 2>&1; then
  echo "Node.js is required but was not found." >&2
  echo "Install Node 18+ (e.g. https://github.com/nodesource/distributions) and re-run." >&2
  exit 1
fi
if ! command -v npm >/dev/null 2>&1; then
  echo "npm is required but was not found." >&2
  exit 1
fi

echo "==> Installing to $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"

echo "==> Downloading agent from $AGENT_URL"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$AGENT_URL" -o "$INSTALL_DIR/nebula-agent.mjs"
else
  wget -qO "$INSTALL_DIR/nebula-agent.mjs" "$AGENT_URL"
fi

echo "==> Installing dependency (systeminformation)"
cd "$INSTALL_DIR"
[ -f package.json ] || echo '{"name":"nebula-agent","private":true,"type":"module"}' > package.json
npm install --omit=dev systeminformation >/dev/null 2>&1

# --- systemd service ---
echo "==> Creating systemd service nebula-agent"
cat > /etc/systemd/system/nebula-agent.service <<UNIT
[Unit]
Description=Nebula monitoring agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
Environment=NEBULA_AGENT_PORT=$PORT
Environment=NEBULA_AGENT_TOKEN=$TOKEN
Environment=NEBULA_REPORT_URL=$REPORT_URL
ExecStart=$(command -v node) $INSTALL_DIR/nebula-agent.mjs
Restart=always
RestartSec=5
WorkingDirectory=$INSTALL_DIR

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now nebula-agent >/dev/null 2>&1
sleep 2

if systemctl is-active --quiet nebula-agent; then
  echo ""
  echo "==> Nebula agent is running (push mode)."
  echo "    It reports to $REPORT_URL every few seconds."
  echo "    The node should now appear in your Nebula dashboard — no further steps."
  echo ""
  echo "Logs:   journalctl -u nebula-agent -f"
  echo "Local:  http://127.0.0.1:$PORT/metrics"
else
  echo "Agent failed to start. Check: journalctl -u nebula-agent -n 50" >&2
  exit 1
fi
