#!/bin/bash
# Stub environment for fp-driver-v5.sh (sha 6f409f91) failure-path exercises.
#
# STUBS ONLY, and that now includes the INSTRUMENTS: doyle granted me no live
# probe, so census.ps1 / cpubracket.ps1 / runner-census.ps1 / portfields.ps1 /
# d1_render.py are stubs sitting at the instrument names the driver expects.
# Nothing here runs cargo, starts a listener, elevates, reads the real firewall
# store, or touches a rule. Every stub RECORDS the requested action, in order.
set -u
RIG="$(cd "$(dirname "$0")" && pwd)"
BIN="$RIG/bin"          # PATH stubs (cargo, gh, pwsh, python, powershell.exe)
FPBIN="$RIG/work/fp-bin" # instrument stubs, at the names the driver invokes
mkdir -p "$BIN" "$FPBIN"

cat > "$BIN/_log" <<'EOL'
#!/bin/bash
n=$(( $(wc -l < "$RIGLOG/actions.log" 2>/dev/null || echo 0) + 1 ))
printf '%03d %-10s %s\n' "$n" "$1" "$2" >> "$RIGLOG/actions.log"
EOL
chmod +x "$BIN/_log"

# ---- the PRODUCT. Records the verb and the opt-out state; performs nothing.
# No privilege is inferred or claimed anywhere in this rig.
cat > "$RIG/spt-stub.sh" <<'EOS'
#!/bin/bash
"$RIGBIN/_log" SPT "verb=[$*] NO_FIREWALL=${SPT_INSTALL_NO_FIREWALL-<REMOVED>}"
case "${FP_SPT_MODE:-noop}" in
  arm_a_trial|signal)
    printf 'leg=verify-query outcome=completed ms=42\n' >&2
    printf 'LAN_FIREWALL_VERIFIED\n'
    # Deterministic signal injection: the stub raises the signal in the DRIVER
    # itself at a named point, so nothing races a sleep.
    if [ -n "${FP_SIGNAL_ON:-}" ] && [ -n "${FP_DRIVER_PID:-}" ]; then
      n=$(cat "$RIGLOG/spt-count" 2>/dev/null || echo 0); n=$((n+1)); echo "$n" > "$RIGLOG/spt-count"
      if [ "$n" -eq "$FP_SIGNAL_ON" ]; then
        "$RIGBIN/_log" MARK "SIGNAL_INJECTED_INTO_DRIVER pid=$FP_DRIVER_PID at product invocation $n"
        kill -TERM "$FP_DRIVER_PID"
      fi
    fi
    exit 0 ;;
  *) exit 0 ;;
esac
EOS
chmod +x "$RIG/spt-stub.sh"

cat > "$BIN/cargo" <<'EOC'
#!/bin/bash
"$RIGBIN/_log" CARGO "argv=[$*] cwd=$PWD"
# Shaped to the contract v6 actually parses (read from the driver, not guessed):
# exactly one ^public_hex: and one ^seed_hex: line, 64 lowercase hex each, plus the
# debug-pin echo whose --public-key must equal the public_hex (v6 cross-checks them).
PUB=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
SEED=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
case "$*" in
  *debug-keygen*)
      printf 'key_id:     fp-debug-2026\n'
      printf 'public_hex: %s\n' "$PUB"
      printf 'seed_hex:   %s\n' "$SEED"
      printf 'next: cargo run -p xtask -- debug-pin --key-id fp-debug-2026 --public-key %s\n' "$PUB"
      exit 0 ;;
  *debug-rollout*)
      # SYNTHETIC FIXTURE, authorized by doyle as a test INPUT (option A).
      # It is produced by the stub standing in for the command that would really
      # have staged it, so it lands only after the driver created its isolated
      # home and only inside that home. The bytes are this rig's harmless bash
      # stub -- no product executable, no signing credential, nothing built.
      # CONSEQUENCE, to be published with every result: S5's three-way provenance
      # is satisfied BY CONSTRUCTION here and tests nothing about real provenance.
      stage=$(printf '%s' "$*" | sed -n 's/.*--stage-dir \([^ ]*\).*/\1/p')
      if [ -n "$stage" ] && [ -n "${FP_EXE:-}" ]; then
        mkdir -p "$stage/artifacts"
        cp "$FP_EXE" "$stage/artifacts/x86_64-pc-windows-msvc.bin"
        sha=$(sha256sum "$FP_EXE" | awk '{print $1}')
        "/c/Program Files/Python312/python" -c 'import json,sys
sha, out = sys.argv[1], sys.argv[2]
meta = {"artifacts": {"x86_64-pc-windows-msvc": {"artifact_sha256": sha}}}
json.dump({"metadata_json": json.dumps(meta)}, open(out, "w", encoding="utf-8"))' "$sha" "$stage/release.json"
        printf 'SYNTHETIC TEST FIXTURE -- generated by the stub rig, not by a build.\nartifacts/x86_64-pc-windows-msvc.bin is a copy of the rig bash stub.\nrelease.json carries that file sha256 as artifact_sha256 so S5 agrees BY CONSTRUCTION.\nS5 here proves nothing about real provenance, signing or the product.\n' \
          > "$stage/SYNTHETIC-FIXTURE-README.txt"
        "$RIGBIN/_log" FIXTURE "staged synthetic artifact+metadata under $stage sha=$sha"
      fi
      printf 'DEBUG_ROLLOUT_STAGED version=1 channel=debug platforms=1 stage_dir=%s\n' "$stage"
      exit 0 ;;
  *debug-mark-applied*) printf 'DEBUG_MARKED_APPLIED version=1 releases=1\n'; exit 0 ;;
esac
exit 0
EOC
chmod +x "$BIN/cargo"

cat > "$BIN/gh" <<'EOG'
#!/bin/bash
"$RIGBIN/_log" GH "argv=[$*]"
printf '[]\n'
EOG
chmod +x "$BIN/gh"

cat > "$BIN/powershell.exe" <<'EOW'
#!/bin/bash
"$RIGBIN/_log" PWSH_ENC "argv=[$*]"
printf '{}\n'
EOW
chmod +x "$BIN/powershell.exe"

# A stub that answers EVERY call the same way is not an instrument, it is noise:
# the first version fed d1_render's PRECHECK text to the driver's CI-json parser,
# which then asked gh to view runs named "Named-Rules=1". Dispatch, or do not stub.
cat > "$BIN/python" <<'EOP'
#!/bin/bash
"$RIGBIN/_log" PYTHON "argv=[$*]"
case "$*" in
  *d1_render*)
      # d1_capture writes --out <file> and then feeds it to powershell
      # -EncodedCommand, so the stub must actually produce that file.
      out=$(printf '%s' "$*" | sed -n 's/.*--out \([^ ]*\).*/\1/p')
      [ -n "$out" ] && printf 'e30=\n' > "$out"
      printf 'PRECHECK Named-Rules=1 PersistentStore=0 Get-NetIPAddress=1 ActiveStore=2\n'
      exit 0 ;;
  *)  # real interpreter for the driver's own inline parsing; reads only files
      # this rig wrote. No host probe, no network.
      exec "/c/Program Files/Python312/python" "$@" ;;
esac
EOP
chmod +x "$BIN/python"

# ---- pwsh: -Command probes (capacity, elevation) and -File instruments.
cat > "$BIN/pwsh" <<'EOZ'
#!/bin/bash
"$RIGBIN/_log" PWSH "argv=[$*]"
file=""; tag=""; outdir=""; port=""; cmd=""
while [ $# -gt 0 ]; do
  case "$1" in
    -File)    file="$2"; shift 2 ;;
    -Tag)     tag="$2";  shift 2 ;;
    -OutDir)  outdir="$2"; shift 2 ;;
    -Port)    port="$2"; shift 2 ;;
    -Command) cmd="$2"; shift 2 ;;
    *) shift ;;
  esac
done
if [ -n "$cmd" ]; then
  case "$cmd" in
    *IsInRole*)      printf '%s\n' "${FP_ELEVATED:-False}"; exit 0 ;;
    *Get-PSDrive*)   printf 'FREE_GIB=%s\n' "${FP_FREE_GIB:-124.00}"; exit 0 ;;
    *)               printf 'OK\n'; exit 0 ;;
  esac
fi
case "$(basename "$file")" in
  runner-census.ps1)
      printf 'RUNNER_CENSUS self_seen=YES cargo_build=%s runner_descended=0 shim_unresolved=0 analyzer=0 valid=YES\n' "${FP_CARGO_BUILD:-0}"
      printf 'RUNNER_WORKER=ABSENT\n'; exit 0 ;;
  cpubracket.ps1)    printf 'bracket tag=%s total_cpus_3s=0.10 valid=YES\n' "$tag"; exit 0 ;;
  census.ps1)
      printf 'tag=%s ctl_5470=1 ctl_sptexe=1 valid=YES subj_group=%s subj_29470=%s\n' \
        "$tag" "${FP_CENSUS_GROUP:-0}" "${FP_CENSUS_29470:-0}" >> "$outdir/census.log"
      printf 'tag=%s ctl_5470=1 ctl_sptexe=1 valid=YES subj_group=%s subj_29470=%s\n' \
        "$tag" "${FP_CENSUS_GROUP:-0}" "${FP_CENSUS_29470:-0}"
      exit 0 ;;
  portfields.ps1)
      # Contract READ from v6, not guessed: port_at greps 'tag=<tag> .* valid=YES'
      # in portfields.log; trial() additionally requires listener_state=READ on the
      # -up row and a 'Path=<EXE>' line inside the snapshot FILE.
      printf 'tag=%s port=%s listener_state=READ listeners=1 valid=YES\n' "$tag" "$port"
      { printf 'Name=spt-lan Enabled=True Direction=Inbound Action=Allow Program=%s\n' "${FP_EXE:-stub}"
        printf 'Listener pid=1234 Path=%s start=2026-09-12T00:00:00Z\n' "${FP_EXE:-stub}"; } \
        > "$outdir/portfields-$port-$tag.txt"
      exit 0 ;;
esac
exit 0
EOZ
chmod +x "$BIN/pwsh"

# ---- instrument stubs at the driver's own names. They do nothing; the pwsh and
# python stubs above answer for them. They exist so the driver's INSTRUMENTS
# hashing step has files to hash.
for f in census.ps1 cpubracket.ps1 runner-census.ps1 portfields.ps1; do
  printf '# STUB instrument, not todlando'"'"'s. No host is read by this file.\n' > "$FPBIN/$f"
done
printf '# STUB d1_render, not todlando'"'"'s.\n' > "$FPBIN/d1_render.py"

echo "v5 stubs built: $BIN ; instrument stubs: $FPBIN"
