#!/usr/bin/env bash
# Installs the build.slice confinement wrapper (git-hook-confine.sh) in front
# of a repo's pre-commit/pre-push hooks — local-only (git-dir-local, never
# committed), fail-open, reversible. Closes §7 "git-hook escapee seam" from
# ANNOYANCE_FATIGUE.md: pre-commit/pre-push builds ran directly in app.slice,
# uncapped and swap-thrash-able.
#
# Usage: install-git-hook-confine.sh <repo-path>
# Reverse: git -C <repo> config --unset core.hooksPath
set -euo pipefail

repo="${1:?usage: install-git-hook-confine.sh <repo-path>}"
confine="$HOME/.claude/bin/git-hook-confine.sh"

git_dir="$(git -C "$repo" rev-parse --absolute-git-dir)"
current_hooks_path="$(git -C "$repo" config core.hooksPath || true)"

wrapper_dir="$git_dir/hooks-confine"

if [ "$current_hooks_path" = "$wrapper_dir" ]; then
  echo "[$repo] already installed -> $wrapper_dir"
  exit 0
fi

# Resolve the ORIGINAL hook dir (what core.hooksPath pointed to before us, or
# the git default) so the wrapper can chain to it.
if [ -n "$current_hooks_path" ]; then
  case "$current_hooks_path" in
    /*) orig_hooks_dir="$current_hooks_path" ;;
    *)  orig_hooks_dir="$(cd "$repo" && cd "$current_hooks_path" && pwd)" ;;
  esac
else
  orig_hooks_dir="$git_dir/hooks"
fi

mkdir -p "$wrapper_dir"

installed=0
for name in pre-commit pre-push; do
  real="$orig_hooks_dir/$name"
  if [ -x "$real" ]; then
    cat > "$wrapper_dir/$name" <<EOF
#!/usr/bin/env bash
exec "$confine" "$real" "\$@"
EOF
    chmod +x "$wrapper_dir/$name"
    installed=1
    echo "[$repo] wrapped $name -> $real"
  fi
done

if [ "$installed" -eq 0 ]; then
  echo "[$repo] no pre-commit/pre-push found under $orig_hooks_dir -- nothing to wrap"
  rmdir "$wrapper_dir" 2>/dev/null || true
  exit 0
fi

git -C "$repo" config core.hooksPath "$wrapper_dir"
echo "[$repo] core.hooksPath -> $wrapper_dir"
