#!/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.
#
# 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 -uo pipefail

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

GUARD_LIB="$SHIM_DIR/../lib/shim-guard.sh"
[[ -r "$GUARD_LIB" ]] || { echo "$name: kill-guard shim cannot read $GUARD_LIB — refusing" >&2; exit 78; }
# shellcheck source=../lib/shim-guard.sh
source "$GUARD_LIB"
shim_guard_enter "$name"

real="$(shim_resolve_real "$name" "$SHIM_DIR")" || real=""
[[ -n "$real" ]] || { echo "$name: command not found (kill-guard shim found no real binary outside $SHIM_DIR)" >&2; exit 127; }
shim_guard_clear "$name"

[[ "$SHIM_REENTRY" == 1 ]] && exec "$real" "$@"

# 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

# `node` in this directory is a symlink to _cpu-guard-shim.sh, so a bare-name call here
# runs a shim from inside the shim directory. Resolve outside it, and refuse the kill when
# the guard exists but cannot be run — an unguarded kill is the failure this shim prevents.
if [[ -r "$GUARD" ]]; then
  node_real="$(shim_resolve_real node "$SHIM_DIR")" || node_real=""
  if [[ -z "$node_real" ]]; then
    echo "$name: kill-guard cannot run $GUARD (no node outside $SHIM_DIR) — refusing" >&2
    exit 78
  fi
  "$node_real" "$GUARD" --argv "$name" "$@" || exit 1
fi

exec "$real" "$@"
