#!/usr/bin/env bash
set -Eeuo pipefail

if (($# != 1)); then
  echo "usage: $0 tools/github-credential-residue/README.md" >&2
  exit 64
fi

repo_root=$(git rev-parse --show-toplevel)
case_path=$(python3 - "$1" <<'PY'
import os
import sys

print(os.path.realpath(sys.argv[1]))
PY
)
case "$case_path" in
  "$repo_root"/tools/github-credential-residue/README.md) ;;
  *) echo "case must be the approved GitHub credential residue tools check" >&2; exit 64 ;;
esac
[[ -f "$case_path" ]] || {
  echo "spec case is missing: $case_path" >&2
  exit 1
}

script=$(mktemp "${TMPDIR:-/tmp}/cp9-tools-check.XXXXXX")
trap 'rm -f "$script"' EXIT
python3 - "$case_path" "$script" <<'PY'
import pathlib
import shlex
import sys

source = pathlib.Path(sys.argv[1])
target = pathlib.Path(sys.argv[2])
inside = False
blocks = 0
lines = [f"rm -f {shlex.quote(str(target))}\n"]
for line in source.read_text(encoding="utf-8").splitlines(keepends=True):
    fence = line.strip()
    if not inside and fence == "```bash":
        inside = True
        blocks += 1
    elif inside and fence == "```":
        inside = False
        lines.append("\n")
    elif inside:
        lines.append(line)
if inside or blocks == 0:
    raise SystemExit(f"invalid Bash fences in {source}")
target.write_text("".join(lines), encoding="utf-8")
PY

cd "$repo_root"
exec bash "$script"
