#!/usr/bin/env bash
# Wires wrapper-reinvoke-lint.py into a repo's active pre-commit hook, so the re-entrant
# wrapper shape cannot be committed. Idempotent; the block is marker-delimited and
# appended, leaving any existing hook body (slopgate) untouched.
#
# usage: install-commit-hook.sh [repo-path]     (default: this checkout)
# Reverse: delete the marked block from the hook the script names.
set -euo pipefail

repo="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)}"
hooks_path="$(git -C "$repo" config core.hooksPath || true)"
if [ -z "$hooks_path" ]; then
  hooks_path="$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir)/hooks"
fi
case "$hooks_path" in /*) ;; *) hooks_path="$repo/$hooks_path" ;; esac
hook="$hooks_path/pre-commit"

if [ -f "$hook" ] && grep -qF 'wrapper-reinvoke-lint v1 BEGIN' "$hook"; then
  echo "already installed -> $hook"
  exit 0
fi

mkdir -p "$hooks_path"
if [ ! -f "$hook" ]; then
  printf '#!/usr/bin/env bash\n' >"$hook"
fi

cat >>"$hook" <<'HOOK'
# wrapper-reinvoke-lint v1 BEGIN
# A PATH wrapper that re-invokes the command it wraps by bare name fork-bombs the machine.
WRL_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
WRL_LINT="$WRL_ROOT/modules/workstation/claude/lint/wrapper-reinvoke-lint.py"
if [ -n "$WRL_ROOT" ] && [ -f "$WRL_LINT" ] &&
   git diff --cached --name-only | grep -q '^modules/workstation/claude/bin/'; then
  python3 "$WRL_LINT" "$WRL_ROOT/modules/workstation/claude/bin" || exit 1
fi
# wrapper-reinvoke-lint v1 END
HOOK
chmod +x "$hook"
echo "installed -> $hook"
