#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# rikkiti-enroll [--admin] <code> [name] — join this box to the company Rikkiti fleet.
# rikkiti-enroll [--admin] --resume      — carry on waiting for an approval that took longer than 15 minutes.
#   (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; RESUME=0
if [ "${1:-}" = "--admin" ]; then ADMIN=1; shift; fi
if [ "${1:-}" = "--resume" ]; then RESUME=1; shift; fi
[ "$RESUME" = 1 ] || CODE="${1:?usage: rikkiti-enroll [--admin] <code> [name]   |   rikkiti-enroll [--admin] --resume}"
HUB="${RIK_HUB_HOST:-hub.rikkiti.org}"
BASE="${RIK_HUB_URL:-https://$HUB}"                              # (the tests: a throwaway hub on this machine)
CACERT="${RIK_BOOT_CACERT:-/etc/ssl/certs/ca-certificates.crt}"  # verify the LE server cert

if [ "$ADMIN" = 1 ]; then
	[ "$RESUME" = 1 ] || 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
	[ "$RESUME" = 1 ] || NAME="${2:-$(hostname)}"
	DIR="${RIK_REMOTE_DIR:-$HOME/.config/rikkiti/remote}"
	KEYFILE="$DIR/nostr.sec"        # agentd's default RIK_AUTH_KEY
fi
# The key being enrolled waits HERE until IT approves it, and only then takes the working key's place. (It used to be
# written straight over the working key: a mistyped code on an enrolled box deleted its identity, and one left
# waiting past the 15 minutes kept a key the hub had never heard of — offline either way, retrying for good.)
NEWKEY="$KEYFILE.enrolling"
WAITING="$KEYFILE.enrolling.request"   # the request's id and name, to carry on waiting with --resume

if [ "$RESUME" = 1 ]; then
	[ -s "$NEWKEY" ] && [ -s "$WAITING" ] || { echo "enroll: nothing is waiting for approval here."; exit 1; }
	id=$(sed -n 1p "$WAITING"); NAME=$(sed -n 2p "$WAITING")
	echo "enroll: carrying on waiting for IT approval (request $id, id=$NAME) ..."
else
	# 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"
	( umask 077; printf '%s' "$SEC" > "$NEWKEY" )   # private from the moment it exists
	rm -f "$WAITING"

	echo "enroll: submitting pubkey to $HUB ..."
	reply=$(curl -sS --cacert "$CACERT" \
	  -H "X-Enroll-Code: $CODE" -H "X-Enroll-Name: $NAME" -H "X-Enroll-Pubkey: $PUB" \
	  "$BASE/enroll" || true)
	id=$(printf '%s' "$reply" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p')
	if [ -z "$id" ]; then
		rm -f "$NEWKEY"   # the key that was never enrolled; the working one, if there is one, is as it was
		echo "enroll: rejected${reply:+: $reply}"
		[ -n "$reply" ] || echo "enroll: (a bad or already-used code, or the hub couldn't be reached)"
		exit 1
	fi
	( umask 077; printf '%s\n%s\n' "$id" "$NAME" > "$WAITING" )
	echo "enroll: submitted as '$NAME' — waiting for IT approval (request $id) ..."
fi
# (the connector, for a device's agent below, when resuming)
if [ -z "${CONNECT:-}" ]; then
	CONNECT=""
	for c in rikkiti-connect wsbridge; do command -v "$c" >/dev/null 2>&1 && { CONNECT="$c"; break; }; done
fi

for _ in $(seq 1 "${RIK_ENROLL_TRIES:-180}"); do   # up to 15 min
  resp=$(curl -sS --cacert "$CACERT" "$BASE/enroll/status?id=$id" 2>/dev/null || true)
  if printf '%s' "$resp" | grep -q approved; then
    mv -f "$NEWKEY" "$KEYFILE"; chmod 600 "$KEYFILE"; rm -f "$WAITING"   # approved: now it's this box's key

    # ── 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
    # 1b) Whether support gets in without someone here allowing it is THIS machine's to say (the hub can't turn the
    #     asking off). A machine joining now starts with the asking on; one that has already said keeps its word.
    #     Turn it off, for a machine nobody sits at, in Settings ▸ Privacy ▸ Remote desktop ▸ Managed support.
    grep -q '^[[:space:]]*fleet_unattended[[:space:]]*=' "$CONF" || printf 'fleet_unattended = false\n' >> "$CONF"

    AS="$HOME/.config/rikkiti/autostart.conf"; mkdir -p "$(dirname "$AS")"; touch "$AS"
    if [ -f /usr/lib/systemd/user/rikkiti-agentd.service ]; then
      # 2) The agent and the RDP server it hands connections to are systemd --user services (supervised, restarted
      #    if they crash): enable both, now and at every login. And no autostart.conf line for the agent as well —
      #    that ran a second, unsupervised agent beside the service's (every event twice on the hub; 2026-09-30).
      grep -v 'agentd --autostart' "$AS" > "$AS.tmp" 2>/dev/null && mv "$AS.tmp" "$AS" || true
      systemctl --user daemon-reload 2>/dev/null
      systemctl --user enable --now rikkiti-agentd.service rikkiti-remote.service 2>/dev/null ||
        echo "enroll: couldn't start the services — Settings ▸ Privacy ▸ Remote desktop starts them when opened."
      echo "enroll: fleet agent and remote desktop server started, and set to start at login — this box is now online."
      echo "enroll: support signs in with the Remote desktop password (Settings ▸ Privacy ▸ Remote desktop)."
      exit 0
    fi

    # 2) (No services: an older desktop.) Persist agentd across logins (idempotent), with RIK_AUTH=nostr in the env.
    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
  if [ "$(printf '%s' "$resp" | tr -d '\r\n')" = unknown ]; then   # no longer waiting, and not approved: turned down
    rm -f "$NEWKEY" "$WAITING"
    echo "enroll: IT turned the request down. Nothing here has changed."
    exit 1
  fi
  sleep "${RIK_ENROLL_SLEEP:-5}"
done
echo "enroll: not approved yet. The request is still waiting with IT, and nothing here has changed."
echo "enroll: once they've approved it, finish with:  rikkiti-enroll$([ "$ADMIN" = 1 ] && echo ' --admin') --resume"
exit 1
