#!/usr/bin/env bash
# Both-ways proof for the wrapper re-entry lint, plus a scan of the wrapper bodies that
# are actually installed on PATH. A wrapper that re-enters itself fork-bombed this
# workstation three times in one week; this suite is what stops the shape landing again.
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
LINT="$ROOT/modules/workstation/claude/lint/wrapper-reinvoke-lint.py"
PASS=0; FAIL=0
ok()  { PASS=$((PASS+1)); printf 'ok   %s\n' "$1"; }
no()  { FAIL=$((FAIL+1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

mk() { mkdir -p "$TMP/$1"; }

# Correct shape: absolute target, resolved while skipping its own directory.
mk good
cat >"$TMP/good/_good-shim.sh" <<'EOF'
#!/usr/bin/env bash
name="$(basename -- "$0")"
SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
real=""
IFS=':' read -ra _parts <<< "$PATH"
for _d in "${_parts[@]}"; do
  [[ "$_d" == "$SHIM_DIR" ]] && continue
  [[ -x "$_d/$name" ]] && { real="$_d/$name"; break; }
done
[[ -n "$real" ]] || { echo "$name: no real binary outside $SHIM_DIR" >&2; exit 127; }
exec "$real" "$@"
EOF
ln -s _good-shim.sh "$TMP/good/git"

# The shape that bombed: the wrapper runs the wrapped name, which PATH resolves back to it.
mk bare
cat >"$TMP/bare/_bare-shim.sh" <<'EOF'
#!/usr/bin/env bash
echo "checking" >&2
exec git "$@"
EOF
ln -s _bare-shim.sh "$TMP/bare/git"

# Dynamic variant: resolves through PATH with nothing that excludes its own directory.
mk unbounded
cat >"$TMP/unbounded/_unbounded-shim.sh" <<'EOF'
#!/usr/bin/env bash
name="$(basename -- "$0")"
real="$(command -v "$name")"
exec "$real" "$@"
EOF
ln -s _unbounded-shim.sh "$TMP/unbounded/pnpm"

out=$(python3 "$LINT" "$TMP/good" 2>&1); rc=$?
[[ $rc -eq 0 ]] && ok "correctly-written wrapper accepted" || no "correctly-written wrapper accepted" "rc=$rc $out"

out=$(python3 "$LINT" "$TMP/bare" 2>&1); rc=$?
[[ $rc -ne 0 && "$out" == *W1* && "$out" == *"'git'"* ]] \
  && ok "bare re-invocation of the wrapped command rejected" \
  || no "bare re-invocation of the wrapped command rejected" "rc=$rc $out"

out=$(python3 "$LINT" "$TMP/unbounded" 2>&1); rc=$?
[[ $rc -ne 0 && "$out" == *W2* ]] \
  && ok "PATH resolution without a re-entry bound rejected" \
  || no "PATH resolution without a re-entry bound rejected" "rc=$rc $out"

out=$(python3 "$LINT" "$ROOT/modules/workstation/claude/bin" 2>&1); rc=$?
[[ $rc -eq 0 ]] && ok "repo wrapper bodies clean" || no "repo wrapper bodies clean" "$out"

INSTALLED="$HOME/.claude/bin"
if [[ -d "$INSTALLED" && "$(realpath "$INSTALLED")" != "$(realpath "$ROOT/modules/workstation/claude/bin")" ]]; then
  out=$(python3 "$LINT" "$INSTALLED" 2>&1); rc=$?
  [[ $rc -eq 0 ]] && ok "installed wrapper bodies on PATH clean" || no "installed wrapper bodies on PATH clean" "$out"
fi

printf 'wrapper-reinvoke-lint.test: PASS=%d FAIL=%d\n' "$PASS" "$FAIL"
[[ "$FAIL" -eq 0 ]]
