#!/usr/bin/env bash
# Global git hook dispatcher (core.hooksPath target).
# 1. commit-msg: strip AI co-author/watermark trailers the owner does not want in history.
# 2. Every hook: chain to the repo's own .git/hooks/<name> so per-repo hooks (husky-less
#    repos, land guards, lint-staged) still fire — a global hooksPath otherwise SHADOWS them.
# Invoked under its own basename via one symlink per hook name.
set -uo pipefail
hook="${0##*/}"

if [ "$hook" = "commit-msg" ] && [ "${1:-}" ] && [ -f "${1:-}" ]; then
  msg="$1"
  stripped="$(mktemp "${TMPDIR:-/tmp}/od-commit-msg.XXXXXX")"
  # Drop AI attribution lines regardless of casing/model name:
  #   Co-Authored-By: Claude ... / ...@anthropic.com
  #   Generated with [Claude Code] (and its 🤖 prefix line)
  grep -viE '^[[:space:]]*Co-Authored-By:[[:space:]]*(Claude|.*<[^>]*anthropic\.com>)|Generated with \[?Claude Code|^[[:space:]]*🤖[[:space:]]*$' "$msg" >"$stripped" 2>/dev/null || cp "$msg" "$stripped"
  # Collapse the trailing blank lines a removed trailer leaves behind.
  awk 'BEGIN{n=0} {lines[NR]=$0} END{last=NR; while(last>0 && lines[last] ~ /^[[:space:]]*$/) last--; for(i=1;i<=last;i++) print lines[i]}' "$stripped" >"$msg"
  rm -f "$stripped"
fi

git_dir="$(git rev-parse --git-dir 2>/dev/null || true)"
local_hook="${git_dir:+$git_dir/hooks/$hook}"
if [ -n "$local_hook" ] && [ -x "$local_hook" ]; then
  exec "$local_hook" "$@"
fi
exit 0
