#!/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.
#
# OD_PATH_SHIM_MARKER — identifies this file to every shim resolver, so a second copy
# of it on PATH is rejected as a candidate instead of being invoked as the "real"
# binary (wrapper invoking itself = unbounded fork loop).
set -e
name="${0##*/}"
SHIM_DIR="$(cd "$(dirname "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd)"

GUARD_LIB="$SHIM_DIR/../lib/shim-guard.sh"
if [[ ! -r "$GUARD_LIB" ]]; then
  echo "$name: cpu-guard shim cannot read $GUARD_LIB — refusing" >&2
  exit 78
fi
# shellcheck source=../lib/shim-guard.sh
source "$GUARD_LIB"
shim_guard_enter "$name"

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

if [[ "$SHIM_REENTRY" == 1 ]]; then
  exec "$real" "$@"
fi

# `npx -y context-mode hook ...` is wired into cursor-agent's per-tool-call hooks, and npx
# re-resolves the package every time: measured 2.1 s CPU idle, 7.5 s under load, against
# 0.27 s for the already-installed bundle with byte-identical stdout. No install cached =>
# fall through to real npx, which is what installs it.
if [[ "$name" == npx ]]; then
  npx_args=("$@")
  [[ "${npx_args[0]:-}" == "-y" || "${npx_args[0]:-}" == "--yes" ]] && npx_args=("${npx_args[@]:1}")
  if [[ "${npx_args[0]:-}" == "context-mode" ]]; then
    bundle=""
    for candidate in "$HOME"/.npm/_npx/*/node_modules/context-mode/cli.bundle.mjs; do
      [[ -r "$candidate" ]] || continue
      [[ -z "$bundle" || "$candidate" -nt "$bundle" ]] && bundle="$candidate"
    done
    if [[ -n "$bundle" && -x "${OD_BUN:-/usr/bin/bun}" ]]; then
      exec "${OD_BUN:-/usr/bin/bun}" "$bundle" "${npx_args[@]:1}"
    fi
  fi
fi

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