#!/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_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

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

exec "$real" "$@"
