#!/bin/bash
# uhhm-ssh-enroll: give THIS machine its own SSH identity for the current
# user and register the public key with kanidm, so sshd on any corp host
# authorises it. Run as the logging-in user (not root). Idempotent.
#
# The private key is generated here and never leaves the machine — only the
# public key goes to kanidm. Revoke a lost machine centrally with:
#   kanidm person ssh delete-publickey <user> <hostname>
set -euo pipefail

u=$(id -un)
host=$(uname -n)
dir="/etc/ssh/local/$u"
key="$dir/id_ed25519"

[ -d "$dir" ] || sudo install -dm700 -o "$(id -u)" -g "$(id -g)" "$dir"
if [ ! -f "$key" ]; then
    ssh-keygen -t ed25519 -N '' -f "$key" -C "$u@$host"
fi

export KANIDM_URL="${KANIDM_URL:-https://id.uhhm.no}"
# Match on the key material (field 2), not the comment/tag.
blob=$(cut -d' ' -f2 "$key.pub")
echo "==> checking kanidm for $u's key from $host (log in if prompted)"
if kanidm person ssh list-publickeys "$u" 2>/dev/null | grep -qF "$blob"; then
    echo "==> already registered; nothing to do."
    exit 0
fi
kanidm person ssh add-publickey "$u" "$host" "$(cat "$key.pub")"
echo "==> done. This machine now authenticates as $u@$host across the fleet."
