#!/usr/bin/env bash
# _cpu-guard-shim.sh — shared body for every PATH shim in this directory.
# Each shim (vitest, tsc, pnpm, npm, ...) is a symlink to this file. PATH-based
# interception works in ANY shell (interactive, non-interactive, subprocess,
# systemd-spawned) because PATH is inherited across exec boundaries — unlike
# bash functions, which are NOT inherited by child processes at all, even when
# the parent sourced ~/.bashrc. That was the actual enforcement gap: the old
# cpu-guard-functions.sh approach only ever worked in the exact interactive
# shell that sourced it.
#
# Package managers (pnpm/npm/yarn/npx) are wrapped too: cpu-guard.sh's taskset
# pins CPU affinity, which is inherited by every child process on fork/exec —
# so `pnpm test` -> vitest workers stay pinned even though vitest itself was
# never resolved through this shim.
set -e
name="$(basename -- "$0")"
SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Resolve the REAL binary, explicitly excluding our own shim dir so we don't
# recurse into ourselves.
real=""
IFS=':' read -ra _parts <<< "$PATH"
for _d in "${_parts[@]}"; do
  [[ "$_d" == "$SHIM_DIR" ]] && continue
  if [[ -x "$_d/$name" && ! -d "$_d/$name" ]]; then
    real="$_d/$name"
    break
  fi
done

if [[ -z "$real" ]]; then
  echo "$name: command not found (cpu-guard shim found no real binary outside $SHIM_DIR)" >&2
  exit 127
fi

if [[ -x "$HOME/.claude/lib/cpu-guard.sh" ]]; then
  exec "$HOME/.claude/lib/cpu-guard.sh" "$real" "$@"
fi
exec "$real" "$@"
