#!/usr/bin/env bash
# NebulaSSH Tunnel Agent — Linux installer.
# Installs the self-contained agent, enrolls it, and enables start-at-boot.
#
#   sudo NEBULASSH_ENROLL_TOKEN=NS-XXXXX ./install-linux.sh
#   (or run without sudo for a per-user systemd service)
set -euo pipefail

RELAY="${RELAY:-https://app.nebulassh.com}"
ENROLL_TOKEN="${NEBULASSH_ENROLL_TOKEN:-}"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) RID="linux-x64" ;;
  aarch64|arm64) RID="linux-arm64" ;;
  *) echo "Unsupported arch: $ARCH"; exit 1 ;;
esac

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BIN_SRC="$SCRIPT_DIR/dist/$RID/nebulassh-tunnel-agent"
[[ -f "$BIN_SRC" ]] || { echo "Agent binary not found: $BIN_SRC (run agent-dotnet8/publish.sh first)"; exit 1; }

if [[ -z "$ENROLL_TOKEN" ]]; then
  read -rp "Enrollment token (Dashboard → Agents & Connector): " ENROLL_TOKEN
fi

if [[ $EUID -eq 0 ]]; then
  INSTALL_DIR="/opt/nebulassh"
else
  INSTALL_DIR="$HOME/.local/share/nebulassh"
fi
mkdir -p "$INSTALL_DIR"
install -m 0755 "$BIN_SRC" "$INSTALL_DIR/nebulassh-tunnel-agent"
echo "Installed → $INSTALL_DIR/nebulassh-tunnel-agent"

# First-run enrollment + enable start-at-boot (the agent writes its own systemd unit).
"$INSTALL_DIR/nebulassh-tunnel-agent" --relay "$RELAY" --enroll-token "$ENROLL_TOKEN" --install
echo ""
echo "Starting the tunnel service…"
if [[ $EUID -eq 0 ]]; then
  systemctl status --no-pager nebulassh-tunnel-agent.service || true
else
  systemctl --user status --no-pager nebulassh-tunnel-agent.service || true
fi
echo ""
echo "Done. The agent auto-starts on every boot and connects out to $RELAY."
echo "Add a Connector session in the dashboard and pick this machine."
