#!/usr/bin/env bash
# _kill-guard-shim.sh — PATH shim body for pkill / killall.
#
# The Claude Code PreToolUse hook covers Claude's Bash tool. This covers every OTHER runtime
# (codex, cursor-agent, and any script they spawn), because PATH is inherited across exec.
# It cannot cover bash's `kill` builtin or a shell redirection into cgroup.kill — those are
# not commands on PATH.
set -uo pipefail

name="$(basename -- "$0")"
SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GUARD="$SHIM_DIR/../lib/kill-guard.mjs"

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
[[ -n "$real" ]] || { echo "$name: command not found (kill-guard shim found no real binary outside $SHIM_DIR)" >&2; exit 127; }

# The guard exists to stop agents, not the machine's owner: a human at a TTY still owns
# every process on it.
if [[ -r "$SHIM_DIR/../lib/session-class.sh" ]]; then
  # shellcheck source=../lib/session-class.sh
  source "$SHIM_DIR/../lib/session-class.sh"
  session_is_human >/dev/null && exec "$real" "$@"
fi

if [[ -r "$GUARD" ]] && command -v node >/dev/null 2>&1; then
  node "$GUARD" --argv "$name" "$@" || exit 1
fi

exec "$real" "$@"
