#!/usr/bin/env bash
# PreToolUse(Bash) deny-gate: block raw `gh pr merge` for gated repos. Free tier
# has no branch protection, so the only enforcement of "the gate must be green
# before merge" is scripts/safe-merge.mjs. Jurisdiction follows the
# `.land-policy` = pr rule (GIT_FATIGUE.md §12): a merge carrying an explicit
# `--repo <other/slug>` targets a repo this guard does not govern.
# Exit 2 blocks the tool call and feeds stderr back to the agent.
set -euo pipefail

GATED_REPOS=('platform-modules/mod')

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("")}})')"

printf '%s' "$cmd" | grep -qE '(^|[^[:alnum:]_-])gh[[:space:]]+pr[[:space:]]+merge' || exit 0
printf '%s' "$cmd" | grep -q 'safe-merge' && exit 0

target="$(printf '%s' "$cmd" | grep -oE '(--repo|-R)[[:space:]=]+[^[:space:]]+' | head -1 | sed -E 's/^(--repo|-R)[[:space:]=]+//' || true)"

if [ -n "$target" ]; then
  gated=0
  for repo in "${GATED_REPOS[@]}"; do
    [ "$target" = "$repo" ] && gated=1
  done
  [ "$gated" -eq 0 ] && exit 0
fi

echo 'Raw `gh pr merge` is blocked for gated repos (no branch protection on free tier). Merge through the fail-closed gate guard, which refuses a PR whose gate is not green:' >&2
echo '  node scripts/safe-merge.mjs <PR> [squash|merge|rebase]' >&2
echo 'In a sibling repo whose gate has another name, point the same guard at it:' >&2
echo '  SAFE_MERGE_GATE="Full gate" node <platform>/scripts/safe-merge.mjs <PR>' >&2
echo 'Merging in a repo with no gate at all? Pass an explicit `--repo <owner>/<name>`.' >&2
exit 2
