#!/usr/bin/env bash
# Nivi Vault Agent installer for Linux.
# Usage:
#   curl -sSL https://get.nivivault.com/agent | sudo bash -s -- --token=<TOKEN>

set -euo pipefail

API_URL="https://api.nivivault.com"
DOWNLOAD_BASE="https://get.nivivault.com"
INSTALL_DIR="/usr/local/bin"
CONFIG_DIR="/etc/nivi-vault"
SERVICE="/etc/systemd/system/nivi-agent.service"
TOKEN=""

for arg in "$@"; do
  case "$arg" in
    --token=*) TOKEN="${arg#*=}" ;;
    --api=*) API_URL="${arg#*=}" ;;
  esac
done

if [[ -z "$TOKEN" ]]; then
  echo "Missing --token. Get one from your Nivi Vault dashboard."
  exit 1
fi

if [[ $EUID -ne 0 ]]; then
  echo "Please run as root."
  exit 1
fi

ARCH=$(uname -m)
case "$ARCH" in
  x86_64) BIN_NAME="nivi-agent-linux-amd64" ;;
  aarch64|arm64) BIN_NAME="nivi-agent-linux-arm64" ;;
  *) echo "Unsupported arch: $ARCH"; exit 1 ;;
esac

echo "==> Downloading $BIN_NAME ..."
curl -fsSL "$DOWNLOAD_BASE/$BIN_NAME" -o "$INSTALL_DIR/nivi-agent"
chmod +x "$INSTALL_DIR/nivi-agent"

mkdir -p "$CONFIG_DIR"
echo "==> Registering agent ..."
"$INSTALL_DIR/nivi-agent" --mode=register --token="$TOKEN" --api="$API_URL"

cat > "$SERVICE" <<EOF
[Unit]
Description=Nivi Vault Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=$INSTALL_DIR/nivi-agent --mode=daemon --api=$API_URL
Restart=always
RestartSec=15
User=root
NoNewPrivileges=true
ProtectSystem=full

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now nivi-agent

echo "==> Done. Agent is running."
systemctl status nivi-agent --no-pager -l | head -n 10 || true
