#!/bin/bash
# Read-only scripts and heredoc bodies are not sends (2026-10-27, prospect desk).
# The /prospect reply checker (mail-replies.mjs) only READS Mail; a file written via
# heredoc whose body mentions a mailer is a file write. Sends after a heredoc still count.
H="${H:-$HOME/.claude/hooks/email-send-gate.sh}"
# Test runs never append to the real gate log: the judge honours EMAIL_GATE_LOG.
if [ -z "${EMAIL_GATE_LOG:-}" ]; then EMAIL_GATE_LOG=$(mktemp /tmp/email-gate-test-log.XXXXXX); _GATE_LOG_TMP=1; fi; export EMAIL_GATE_LOG
pass=0; fail=0
check() {
  local got; got=$(printf '%s' "$3" | "$H")
  local dec="allow"
  case "$got" in *'"permissionDecision":"ask"'*) dec=ask;; *'"permissionDecision":"deny"'*) dec=deny;; esac
  if [ "$dec" = "$2" ]; then pass=$((pass+1)); echo "ok    $1 -> $dec"; else fail=$((fail+1)); echo "FAIL  $1 -> $dec (expected $2)"; echo "      $got" | head -c 400; echo; fi
}
check "prospect-reply-checker-read-only" allow '{"tool_name":"Bash","tool_input":{"description":"Check Mail for replies from ledger addresses","command":"node ~/flow/scripts/prospects/mail-replies.mjs > /tmp/x/replies.out 2>&1; echo \"exit $?\""}}'
check "prospect-reply-checker-bare" allow '{"tool_name":"Bash","tool_input":{"description":"Check replies","command":"node /Users/orenmagid/flow/scripts/prospects/mail-replies.mjs"}}'
check "heredoc-file-body-mentions-mailer" allow '{"tool_name":"Bash","tool_input":{"description":"Create a Flow action","command":"cat > /tmp/x/file-action.mjs <<'"'"'EOF'"'"'\nconst notes = `narrow the (sendmail|mutt|mailx) regex; echo hi | sendmail x@y.com; mail -s hi x@y; curl smtp://h`;\nawait fetch(url, {method: \"POST\"});\nEOF\nnode /tmp/x/file-action.mjs"}}'
check "heredoc-then-real-cli-send-still-caught" deny '{"tool_name":"Bash","tool_input":{"description":"write then mail","command":"cat > /tmp/x/n.txt <<EOF\nhello\nEOF\necho hi | sendmail x@y.com"}}'
check "heredoc-then-scripted-send-still-caught" deny '{"tool_name":"Bash","tool_input":{"description":"write then send","command":"cat > /tmp/x/n.txt <<EOF\nhello\nEOF\nnode scripts/prospects/send-outreach.mjs foo"}}'
check "script-named-send-outreach-still-caught" deny '{"tool_name":"Bash","tool_input":{"description":"run","command":"node ~/flow/scripts/prospects/send-outreach.mjs abe-timmons"}}'
check "script-named-mailer-still-caught" deny '{"tool_name":"Bash","tool_input":{"description":"run","command":"python3 tools/mailer.py --to a@b.com"}}'
check "cf-email-worker-deploy-is-not-a-send" allow '{"tool_name":"Bash","tool_input":{"description":"Render the Cloudflare email body","command":"node ~/flow/scripts/prospects/cf-email.mjs ~/flow/areas/ventures/prospects/drafts/x.md"}}'
check "unterminated-heredoc-still-scanned" deny '{"tool_name":"Bash","tool_input":{"description":"x","command":"cat <<EOF\necho hi | sendmail x@y.com"}}'
echo "passed=$pass failed=$fail"
[ -n "${_GATE_LOG_TMP:-}" ] && rm -f "$EMAIL_GATE_LOG"
[ "$fail" -eq 0 ]
