#!/usr/bin/env bash
# scripts/run-logged.sh <phase-label>
#
# As-executed session logger (DOCFIX-076). Opens a logged interactive subshell;
# EVERYTHING typed and printed is appended to ~/as-executed/<UTC date>-<label>.log
# via script(1). Exit the subshell to stop logging. The verbatim-retrieval rule
# for one-shot/irreversible steps (vault init, CA issuance, authorize-charm)
# depends on these logs EXISTING and being FINDABLE -- see
# docs/as-executed-log-convention.md. Logs stay on the jumphost (secret-adjacent:
# NEVER commit them); commit only the index entry.
#
# Mutates: creates/appends ~/as-executed/<date>-<label>.log (0600, dir 0700).
# Exit: the subshell's exit code (script -e passthrough) | 1 usage/precondition.
# ASCII + LF.
set -uo pipefail
LABEL="${1:-}"
[ -n "$LABEL" ] || { echo "usage: bash scripts/run-logged.sh <phase-label>   (e.g. phase-02-vault)"; exit 1; }
printf '%s' "$LABEL" | grep -qE '^[A-Za-z0-9._-]+$' || { echo "FAIL: label must be [A-Za-z0-9._-]"; exit 1; }
command -v script >/dev/null 2>&1 || { echo "FAIL: util-linux 'script' not found"; exit 1; }
DIR="$HOME/as-executed"; ( umask 077; mkdir -p "$DIR" )
LOG="$DIR/$(date -u +%F)-$LABEL.log"
( umask 077; touch "$LOG" )
echo "== logging to $LOG -- exit the shell to stop =="
# -a append, -q quiet, -e return child exit code
script -aqe "$LOG"
RC=$?
echo "== log closed: $LOG (add an index entry: logs/as-executed-index.md) =="
exit "$RC"
