#!/bin/sh
# pam-zta-gateway-qr — print the root-enrollment QR and nothing else.
#
# The gateway prints the QR to its log once, at start-up, and the journal buries
# it under request lines within a minute: `journalctl -n 300` shows the QR
# somewhere in three hundred lines of JSON, or not at all on a busy gateway.
#
# Only the CURRENT run of the service is read. The enrollment token lives in
# that process's memory, so a QR printed by an earlier run is dead however
# recent it looks — showing it would send the operator to scan a token that
# can no longer work.
#
# Installed as /usr/bin/pam-zta-gateway-qr. Needs root to read the journal.
set -eu

UNIT=pam-zta-gateway

die() { printf '%s\n' "$*" >&2; exit 1; }

command -v journalctl >/dev/null 2>&1 || die "journalctl not found — this command needs systemd."

RUN="$(systemctl show -p InvocationID --value "$UNIT" 2>/dev/null || true)"
[ -n "$RUN" ] || die "$UNIT is not running. Start it with: sudo systemctl start $UNIT"

# The banner is three rule lines: one above the title, one below it, one closing
# the block. Keep from the first to the third and stop reading there, so a long
# journal costs nothing past start-up.
QR="$(journalctl "_SYSTEMD_INVOCATION_ID=$RUN" -o cat --no-pager 2>/dev/null | awk '
  /ROOT ENROLLMENT/ { buf = prev ORS; on = 1; rules = 0 }
  on { buf = buf $0 ORS; if ($0 ~ /^═/ && ++rules == 2) { printf "%s", buf; exit } }
  { prev = $0 }')"

if [ -z "$QR" ]; then
  [ "$(id -u)" -eq 0 ] || die "No QR found. Reading the journal needs root: sudo pam-zta-gateway-qr"
  die "No root-enrollment QR in this run of $UNIT.
Either a root approver is already enrolled, or [server].public_url is not set.
The log says which:  sudo journalctl -u $UNIT -o cat --no-pager | grep '\"enroll_'"
fi

printf '%s\n' "$QR"

# ponytail: the token's expiry is not checked here, only the start time is
# shown; compute it from the banner's "Valid:" line if operators keep scanning
# expired codes.
SINCE="$(systemctl show -p ActiveEnterTimestamp --value "$UNIT" 2>/dev/null || true)"
[ -z "$SINCE" ] || printf '  Printed at service start: %s\n  Expired or already used? sudo systemctl restart %s, then run this again.\n' "$SINCE" "$UNIT" >&2
