#!/bin/sh
# bty-web token rotation helper.
#
# Invoked by the ``bty`` service user via the entry in
# ``/etc/sudoers.d/bty-web``. Generates a fresh URL-safe random
# token, atomically rewrites ``/etc/default/bty-web`` so subsequent
# reads pick up the new value, and prints the new token on stdout
# for the caller to surface to the operator.
#
# Deliberately does NOT restart bty-web.service. Restarting kills
# the active session before the operator sees the new token; let
# the operator copy the value first, then restart manually (or
# reboot) when they're ready. Until restart, the OLD token still
# authenticates.

set -eu

NEW_TOKEN=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')

DEFAULT=/etc/default/bty-web
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

# Replace BTY_WEB_TOKEN= line, leaving everything else untouched.
awk -v t="$NEW_TOKEN" '
    /^BTY_WEB_TOKEN=/ { print "BTY_WEB_TOKEN=" t; next }
    { print }
' "$DEFAULT" > "$TMP"

chown root:bty "$TMP"
chmod 0640 "$TMP"
mv "$TMP" "$DEFAULT"
trap - EXIT

# Print the new token so the caller can surface it. Do not log it
# anywhere else - the caller (bty-web) shows it once in the UI.
printf '%s\n' "$NEW_TOKEN"
