#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# rikkiti-enroll [--admin] <code> [name] — join this box to the company Rikkiti fleet.
#   (no flag)  enrol this machine as a DEVICE (managed box; starts the fleet agent).
#   --admin    onboard this person as an IT console OPERATOR (installs their console
#              key; no agent). The role is set by the code IT minted, not this flag.
#
# NOSTR-KEY model (docs/35): generates this box's secp256k1 keypair LOCALLY via
# `rikkiti-connect keygen` (the private key NEVER leaves the machine), submits the
# PUBLIC key + the one-time enrollment CODE to the Hub, then polls until IT
# approves — at which point the box is in the hub's allow-list and goes online.
# No CSR, no CA, no cert. After approval the device starts agentd (RIK_AUTH=nostr).
#
# Ships in the rikkiti-desktop deb. Settings ▸ Remote ▸ "Join fleet" runs the same
# thing with the code pasted into the GUI.
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail
ADMIN=0
if [ "${1:-}" = "--admin" ]; then ADMIN=1; shift; fi
CODE="${1:?usage: rikkiti-enroll [--admin] <code> [name]}"
HUB="${RIK_HUB_HOST:-hub.rikkiti.org}"
CACERT="${RIK_BOOT_CACERT:-/etc/ssl/certs/ca-certificates.crt}"  # verify the LE server cert

if [ "$ADMIN" = 1 ]; then
	NAME="${2:?admin enrolment needs a user id, e.g.  rikkiti-enroll --admin <code> richard}"
	DIR="${RIK_ADMIN_DIR:-$HOME/.config/rikkiti/remote-admin}"
	KEYFILE="$DIR/operator.sec"
else
	NAME="${2:-$(hostname)}"
	DIR="${RIK_REMOTE_DIR:-$HOME/.config/rikkiti/remote}"
	KEYFILE="$DIR/nostr.sec"        # agentd's default RIK_AUTH_KEY
fi

# Resolve the connector binary (used for keygen now + agentd later).
CONNECT=""
for c in rikkiti-connect wsbridge; do command -v "$c" >/dev/null 2>&1 && { CONNECT="$c"; break; }; done
[ -n "$CONNECT" ] || for c in "$HOME/odin/rikkiti-os/hub-spike/wsbridge" "$HOME/rikkiti-connect-nostr" "$HOME/rik-remote/wsbridge"; do
	[ -x "$c" ] && { CONNECT="$c"; break; }; done
[ -n "$CONNECT" ] || { echo "enroll: no rikkiti-connect binary found"; exit 2; }

echo "enroll: generating this box's keypair (id=$NAME) — the private key never leaves here ..."
kv=$("$CONNECT" keygen 2>/dev/null)
SEC=$(printf '%s\n' "$kv" | sed -n 's/^sec //p')
PUB=$(printf '%s\n' "$kv" | sed -n 's/^pub //p')
[ -n "$SEC" ] && [ -n "$PUB" ] || { echo "enroll: keygen failed"; exit 1; }
mkdir -p "$DIR"; printf '%s' "$SEC" > "$KEYFILE"; chmod 600 "$KEYFILE"

echo "enroll: submitting pubkey to $HUB ..."
id=$(curl -sS --cacert "$CACERT" \
  -H "X-Enroll-Code: $CODE" -H "X-Enroll-Name: $NAME" -H "X-Enroll-Pubkey: $PUB" \
  "https://$HUB/enroll" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p')
[ -n "$id" ] || { echo "enroll: rejected (bad or already-used code?)"; rm -f "$KEYFILE"; exit 1; }
echo "enroll: submitted as '$NAME' — waiting for IT approval (request $id) ..."

for _ in $(seq 1 180); do   # up to 15 min
  resp=$(curl -sS --cacert "$CACERT" "https://$HUB/enroll/status?id=$id" 2>/dev/null || true)
  if printf '%s' "$resp" | grep -q approved; then

    # ── ADMIN: install into the IT console's config; no fleet agent on this box. ──
    if [ "$ADMIN" = 1 ]; then
      echo "enroll: ✓ APPROVED — operator key installed at $KEYFILE"
      CONF="$HOME/.config/rikkiti/remote-admin.conf"; mkdir -p "$(dirname "$CONF")"; touch "$CONF"
      set_conf() { if grep -q "^$1=" "$CONF"; then sed -i "s|^$1=.*|$1=$2|" "$CONF"; else printf '%s=%s\n' "$1" "$2" >> "$CONF"; fi; }
      set_conf host "$HUB"; set_conf authkey "$KEYFILE"
      echo "enroll: this box is now an IT console operator ($NAME)."
      echo "enroll: launch  rikkiti-remote-admin  to connect to + view the fleet."
      exit 0
    fi

    echo "enroll: ✓ APPROVED — this box's key is in the fleet allow-list."

    # 0) Drop the enrolment marker Settings ▸ Remote reads as "enrolled".
    printf '%s\n' "$HUB" > "$DIR/fleet-enrolled"

    # 1) Record the hub so Settings' banner + the agent agree on it.
    CONF="$HOME/.config/rikkiti/remote.conf"; mkdir -p "$(dirname "$CONF")"; touch "$CONF"
    if grep -q '^hub=' "$CONF"; then sed -i "s|^hub=.*|hub=$HUB|" "$CONF"; else printf 'hub=%s\n' "$HUB" >> "$CONF"; fi

    # 2) Persist agentd across logins (idempotent), with RIK_AUTH=nostr in the env.
    AS="$HOME/.config/rikkiti/autostart.conf"; mkdir -p "$(dirname "$AS")"; touch "$AS"
    grep -v 'agentd --autostart' "$AS" > "$AS.tmp" 2>/dev/null && mv "$AS.tmp" "$AS" || true
    printf 'env RIK_AUTH=nostr %s agentd --autostart   # Rikkiti fleet agent (managed by enrollment)\n' "$CONNECT" >> "$AS"

    # 3) …and bring it up NOW so the box goes online without a re-login.
    if ! pgrep -f 'agentd --autostart' >/dev/null 2>&1; then
      mkdir -p "$HOME/.cache/rikkiti"
      setsid env RIK_AUTH=nostr "$CONNECT" agentd --autostart >"$HOME/.cache/rikkiti/agentd.log" 2>&1 &
    fi
    echo "enroll: fleet agent started + set to auto-start on login — this box is now online."
    exit 0
  fi
  sleep 5
done
echo "enroll: timed out waiting for approval (the request stays PENDING; re-run status later)."; exit 1
