#!/usr/bin/env bash
# shim-bare-name.test.sh — static invariant: no PATH shim in claude/bin invokes, by bare
# name, any command that also exists in claude/bin. Such a call resolves through PATH back
# into the shim directory, so a wrapper reaches a wrapper — the shape that fork-bombed this
# machine. Purely static: this suite never executes a shim, so it is safe to run anywhere.
set -uo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN="$HERE/../bin"
PASS=0
FAIL=0

ok() {
  PASS=$((PASS + 1))
  echo "  ok: $1"
}
bad() {
  FAIL=$((FAIL + 1))
  echo "  FAIL: $1"
}

scan() { # $1=bin dir → prints "<file>:<line>:<name>" per violation
  python3 - "$1" <<'PY'
import os, re, sys

bindir = sys.argv[1]


def is_shim(path):
    if not os.path.isfile(path):
        return False
    try:
        with open(path, encoding="utf-8", errors="replace") as fh:
            head = fh.read(8192)
    except OSError:
        return False
    return head.startswith("#!") and re.search(r"(?m)^\s*#.*\bOD_PATH_SHIM_MARKER\b", head) is not None


# A bare-name call is a hazard when the name resolves to a shim: the wrapper then reaches
# wrapper territory. Names in bin/ that are ordinary programs are not this class.
names = {f for f in os.listdir(bindir) if is_shim(os.path.realpath(os.path.join(bindir, f)))}
call = re.compile(
    r"(?:^|[;&|(]|\|\||&&|\$\(|`|\bthen\b|\bdo\b|\belse\b|\bexec\b|\bcommand -v\b)\s*"
    r"([A-Za-z_][\w.-]*)(?=\s|$)"
)
heredoc = re.compile(r"<<-?\s*[\"']?([A-Za-z_]\w*)[\"']?")


def strip_quotes(line):
    return re.sub(r"'[^']*'", "", re.sub(r'"[^"]*"', "", line))


for f in sorted(names):
    p = os.path.join(bindir, f)
    if os.path.islink(p) or not os.path.isfile(p):
        continue
    try:
        text = open(p, encoding="utf-8", errors="replace").read()
    except OSError:
        continue
    if not text.startswith("#!") or "OD_PATH_SHIM_MARKER" not in text:
        continue
    term = None
    for i, line in enumerate(text.splitlines(), 1):
        if term is not None:
            if line.strip() == term:
                term = None
            continue
        stripped = line.strip()
        if stripped.startswith("#"):
            continue
        m = heredoc.search(line)
        if m:
            term = m.group(1)
        for c in call.finditer(strip_quotes(line)):
            if c.group(1) in names:
                print("%s:%d:%s" % (f, i, c.group(1)))
PY
}

echo "=== no shim in bin/ invokes a bin/ name bare ==="
found="$(scan "$BIN")"
if [[ -z "$found" ]]; then
  ok "claude/bin shims call nothing that resolves back into claude/bin"
else
  while IFS= read -r line; do
    bad "bare-name call reaches the shim directory: $line"
  done <<<"$found"
fi

echo "=== the scan detects a planted violation ==="
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/bin"
printf '%s\n' '#!/usr/bin/env bash' '# OD_PATH_SHIM_MARKER' >"$TMP/bin/_cpu-guard-shim.sh"
ln -s _cpu-guard-shim.sh "$TMP/bin/node"
printf '%s\n' '#!/usr/bin/env bash' '# OD_PATH_SHIM_MARKER' 'node --version' >"$TMP/bin/_planted-shim.sh"
planted="$(scan "$TMP/bin")"
if [[ "$planted" == "_planted-shim.sh:3:node" ]]; then
  ok "planted bare-name call is reported"
else
  bad "planted violation not reported (got: '$planted')"
fi

echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
