#!/bin/sh
#
# 拦截带 AI 署名的提交被推上远端。
#
# 存在的理由:commit-msg 只在「新写提交信息」时触发,rebase / merge / cherry-pick
# 搬运旧提交都不经过它,作者身份更是它根本改不了的。仓库里现存几十个未推送的旧分支
# (codex/*、task/*、shz_vide/*),它们的提交仍带 2026-08-30 重写前的署名,
# 任何一次 rebase 合并都会把署名带回远端。这道闸是唯一覆盖该路径的地方。
#
# 判定规则与 scripts/strip-ai-attribution.sh 一致:按邮箱域,不按关键词。
# 因此描述 Copilot / Anthropic provider、复刻 Claude Code 功能的正常提交不受影响。
#
# 启用: git config core.hooksPath .githooks
# 确需绕过: git push --no-verify
#
set -e

z40=$(git hash-object --stdin </dev/null | sed 's/./0/g')
fail=0

while read -r _local_ref local_sha _remote_ref remote_sha; do
  # 删除分支的推送,没有提交要检查
  [ "$local_sha" = "$z40" ] && continue

  if [ "$remote_sha" = "$z40" ]; then
    # 远端新分支:检查所有还没进过任何远端分支的提交
    range="$local_sha --not --remotes"
  else
    range="$remote_sha..$local_sha"
  fi

  # 作者/提交者身份
  bad_id=$(git log $range --format='%H %an <%ae> %cn <%ce>' 2>/dev/null \
    | grep -iE 'noreply@anthropic\.com|copilot-swe-agent|copilot@users\.noreply\.github\.com' \
    | head -5 || true)
  # 署名 trailer 与生成页脚
  bad_msg=$(git log $range --format='%B' 2>/dev/null \
    | grep -iE '^[[:space:]]*(co-authored-by:.*(noreply@anthropic\.com|copilot.*@users\.noreply\.github\.com)|claude-session:|.*generated with \[?claude code)' \
    | head -5 || true)

  if [ -n "$bad_id" ] || [ -n "$bad_msg" ]; then
    fail=1
    echo "推送被拒:以下提交带 AI 署名(本仓库历史不保留第三方署名)" >&2
    [ -n "$bad_id" ]  && { echo "  作者/提交者身份:" >&2; echo "$bad_id"  | sed 's/^/    /' >&2; }
    [ -n "$bad_msg" ] && { echo "  提交信息署名行:" >&2; echo "$bad_msg" | sed 's/^/    /' >&2; }
  fi
done

if [ "$fail" -ne 0 ]; then
  cat >&2 <<'MSG'

处理办法(任选其一):
  1. 重写这批提交的署名后再推:
       git rebase -i --exec 'git commit --amend --no-edit --reset-author' <base>
  2. 用 scripts/strip-ai-attribution.sh 清洗后再推(见 docs/strip-ai-attribution.md)
  3. 确认无需拦截:git push --no-verify
MSG
  exit 1
fi

exit 0
