#!/usr/bin/env bash
# r6 setup+t1 leg runner. usage: leg-runner-r6.sh <request-file> <dry|run> <start-guard-utc>
# env required: GRANT_EXE, GRANT_CAP (grant-tuple pins). Refuses if empty or mismatched.
# doyle r7 (EIWE4Q7U): scrub OWL_*/SPT_* (keep SPT_TEST_EPHEMERAL_ADVISORY_PORTS) before run_exactly;
#   record names before/after to ENV_NAMES; refuse if any must-die name survives.
# hertz (VR72ZRUS): step 7 = pwsh7 -NoProfile -Command "<T1_LAUNCH verbatim>; exit $LASTEXITCODE".
REQ="$1"; MODE="$2"; GUARD="$3"
L="C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/1212783f-c73e-4b6f-a6b2-fa9a428720d5/scratchpad/nonce-ledger.txt"
ENV_NAMES="C:/Users/decid/Documents/projects/spt-core/.spt/preserved/hertz-fp-driver-review/d2/VGCTKD7A-executor-env-names.json"
PWSH7='/c/Program Files/PowerShell/7/pwsh.exe'
MUSTDIE='OWL_SESSION_ID SPT_ENDPOINT_ID SPT_AGENT_ID SPT_ADAPTER SPT_RELEASE_SEED'

tr -d '\r' < "$REQ" > /tmp/leg6-req.$$ ; R=/tmp/leg6-req.$$
N=$(grep -m1 '^nonce: ' "$R" | sed 's/^nonce: //')
RCPT=$(grep -m1 '^receipt_file: ' "$R" | sed 's/^receipt_file: //')
SETUP=$(awk 'f{print; exit} /^run_exactly:$/{f=1}' "$R")
CAP=$(awk 'f{print; exit} /then_run_exactly/{f=1}' "$R")
st() { grep -m1 "stamp_utc_now_to (immediately $1 step $2[,)]" "$R" | sed 's/.*): //'; }
S4=$(st AFTER 2); S6=$(st BEFORE 7); S8=$(st AFTER 7)
# r10 AQ23KKNI: step 1 is initialize_leg_clock, a single PS7 expr emitted under
# leg_clock_begin_powershell: within the "1. initialize_leg_clock" block. Run it verbatim; it
# CreateNew-writes setup-start.utc + elevated-leg-start.epoch + d2-t1.deadline from ONE UTC.
LEGCLK=$(awk '/1\. initialize_leg_clock/{a=1} a&&/leg_clock_begin_powershell:/{f=1;next} f{print;exit}' "$R")
SEXIT=$(grep -m1 'write_the_exit_preserved_in_step_3_to: ' "$R" | sed 's/.*_to: //')
CEXIT=$(grep -m1 'then_write_its_launcher_exit_to: ' "$R" | sed 's/.*_to: //')
EXE_PIN=$(grep -m1 'executable_identity_REQUIRED: sha256 ' "$R" | sed 's/.*sha256 //')
EXE_PATH=$(grep -A1 'executable_identity_REQUIRED' "$R" | sed -n '2p' | sed 's/^ *at //; s/ — .*//')
CAP_PIN=$(grep -m1 'capture_identity_REQUIRED: sha256 ' "$R" | sed 's/.*sha256 //')

for v in N RCPT SETUP CAP LEGCLK S4 S6 S8 SEXIT CEXIT EXE_PIN EXE_PATH; do [ -z "${!v}" ] && { echo "EXTRACT_FAILED $v"; exit 80; }; done
# r6: d2_capture.ps1 is NOT in the T1_LAUNCH line (it lives in d2-t1.argv.json). Its path is
# RIG_ROOT/bin/d2_capture.ps1; RIG_ROOT is a pinned grant value passed in GRANT_RIG_ROOT.
[ -n "$GRANT_CAPPS" ] || { echo "EXTRACT_FAILED GRANT_CAPPS"; exit 80; }
CAPPS="$GRANT_CAPPS"
[ -e "$CAPPS" ] || { echo "CAPPS_ABSENT $CAPPS"; exit 80; }

eh=$(sha256sum "$EXE_PATH" 2>/dev/null | cut -d' ' -f1); ch=$(sha256sum "$CAPPS" 2>/dev/null | cut -d' ' -f1)
echo "NONCE=[$N] EXE_PATH=[$EXE_PATH] CAPPS=[$CAPPS]"
echo "exe_measured=$eh cap_measured=$ch exe_pin_req=$EXE_PIN cap_pin_req=$CAP_PIN"
[ "$eh" = "$EXE_PIN" ] || { echo "EXE_MISMATCH_REQUEST_PIN"; exit 81; }
[ -n "$GRANT_EXE" ] && [ "$eh" = "$GRANT_EXE" ] || { echo "EXE_NOT_GRANT_PIN"; exit 82; }
[ -n "$GRANT_CAP" ] && [ "$ch" = "$GRANT_CAP" ] || { echo "CAP_NOT_GRANT_PIN"; exit 83; }
[ -n "$CAP_PIN" ] && [ "$ch" = "$CAP_PIN" ] || { echo "CAP_MISMATCH_REQUEST_PIN"; exit 83; }
# step-7 shape guard: the request's step-7 line must be a launch-v2.ps1 -File invocation (pinned shape)
printf '%s' "$CAP" | grep -q -- 'launch-v2.ps1' || { echo "STEP7_SHAPE_UNEXPECTED"; exit 84; }
[ -e "$RCPT" ] && { echo "RECEIPT_EXISTS"; exit 85; }
grep -q -- "$N STARTED" "$L" 2>/dev/null && { echo "NONCE_IN_LEDGER"; exit 86; }
[ "$MODE" = run ] || { echo "DRY_OK legclk=[$LEGCLK] setup=[$SETUP] step7_wrapped=[pwsh7 -NoProfile -Command \"<CAP>; exit \$LASTEXITCODE\"]"; exit 0; }
now=$(date -u +%s); lim=$(date -u -d "$GUARD" +%s); [ "$now" -gt "$lim" ] && { echo "NOT_STARTED past guard $GUARD"; exit 90; }

# --- doyle r7 env scrub, in THIS process, before run_exactly ---
before=$(env | grep -oE '^(OWL_[A-Za-z0-9_]*|SPT_[A-Za-z0-9_]*)=' | sed 's/=$//' | sort)
for v in $before; do [ "$v" = SPT_TEST_EPHEMERAL_ADVISORY_PORTS ] && continue; unset "$v"; done
after=$(env | grep -oE '^(OWL_[A-Za-z0-9_]*|SPT_[A-Za-z0-9_]*)=' | sed 's/=$//' | sort)
rem=''; for n in $MUSTDIE; do [ -n "${!n+x}" ] && rem="$rem $n"; done
jarr() { printf '['; local f=1; for x in $1; do [ $f -eq 1 ] && f=0 || printf ','; printf '"%s"' "$x"; done; printf ']'; }
{ printf '{\n  "recorded_utc": "%s", "run_nonce": "%s", "phase": "setup+t1 leg",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$N"
  printf '  "names_before": %s,\n  "names_after": %s,\n' "$(jarr "$before")" "$(jarr "$after")"
  printf '  "must_die": ["OWL_SESSION_ID","SPT_ENDPOINT_ID","SPT_AGENT_ID","SPT_ADAPTER","SPT_RELEASE_SEED"],\n'
  printf '  "must_die_remaining_after_scrub": %s\n}\n' "$(jarr "$rem")"; } > "$ENV_NAMES"
[ -n "$rem" ] && { echo "REFUSE must-die survived:$rem"; printf 'nonce: %s\nREFUSED: elevated env not scrubbed, survivors%s; run_exactly NOT executed\n' "$N" "$rem" > "$RCPT"; exit 87; }

echo "$N STARTED $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$L"
stamp() { MSYS_NO_PATHCONV=1 "$PWSH7" -NoProfile -Command "[DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') | Set-Content -NoNewline -Encoding ascii '$1'"; }
# 1: initialize_leg_clock — run the request's emitted expression verbatim in pwsh7. CreateNew
# means a pre-existing clock file THROWS: that is the intended refusal (never reset). If it
# fails, refuse the leg without running run_exactly.
MSYS_NO_PATHCONV=1 "$PWSH7" -NoProfile -Command "$LEGCLK" || { echo "REFUSE leg_clock_begin failed (pre-existing clock file or write error); run_exactly NOT executed"; printf 'nonce: %s\nREFUSED: leg_clock_begin failed; run_exactly NOT executed\n' "$N" > "$RCPT"; exit 88; }
eval "$SETUP"; SETUP_RC=$?  # 2,3
stamp "$S4"                 # 4
printf '%s' "$SETUP_RC" > "$SEXIT"   # 5
echo "$N SETUP_EXIT=$SETUP_RC $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$L"
stamp "$S6"                 # 6
MSYS_NO_PATHCONV=1 "$PWSH7" -NoProfile -Command "$CAP; exit \$LASTEXITCODE"; CAP_RC=$?   # 7 (hertz VR72ZRUS shape)
printf '%s' "$CAP_RC" > "$CEXIT"
stamp "$S8"                 # 8
echo "$N CAPTURE_EXIT=$CAP_RC $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$L"
printf 'nonce: %s\nexit=%s\nlauncher status recorded separately in %s as %s (native capture exit in d2-t1.native.json)\nexecutable and capture hashes measured by liam before step 1: %s %s\nleg clock initialized by the request-emitted leg_clock_begin expression (CreateNew; setup-start.utc + elevated-leg-start.epoch + d2-t1.deadline=start+120 from one UTC)\nenv scrubbed before run_exactly, must-die survivors: none (see VGCTKD7A-executor-env-names.json)\nall 8 steps run in order under one leg; setup via bash, clock+stamps+t1 via pwsh7\n' "$N" "$SETUP_RC" "$CEXIT" "$CAP_RC" "$eh" "$ch" > "$RCPT"
echo "$N RECEIPT_WRITTEN $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$L"
echo "DONE setup_rc=$SETUP_RC cap_rc=$CAP_RC"
