#!/usr/bin/env bash
# PreToolUse(Bash) deny-gate: block raw `gh pr merge`. Free tier has no branch
# protection, so the only enforcement of "PR Gate must be green before merge"
# is scripts/safe-merge.mjs. This gate forces every merge through it.
# Exit 2 blocks the tool call and feeds stderr back to the agent.
set -euo pipefail

input="$(cat)"
cmd="$(printf '%s' "$input" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.stdout.write(String(JSON.parse(s).tool_input?.command??""))}catch{process.stdout.write("")}})')"

if printf '%s' "$cmd" | grep -qE '(^|[^[:alnum:]_-])gh[[:space:]]+pr[[:space:]]+merge'; then
  if ! printf '%s' "$cmd" | grep -q 'safe-merge'; then
    echo 'Raw `gh pr merge` is blocked (no branch protection on free tier). Merge through the fail-closed gate guard, which refuses a PR whose "PR Gate" is not green:' >&2
    echo '  node scripts/safe-merge.mjs <PR> [squash|merge|rebase]' >&2
    exit 2
  fi
fi
exit 0
