#!/usr/bin/env bash
# publish-gate.sh — Pre-publish IP scanner for forge-audio-public.
# Reads .gate-patterns and greps all publishable source files.
# Exit 1 = leak found, blocks publish. Exit 0 = clean.
set -euo pipefail

REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
GATE_FILE="$REPO_DIR/.gate-patterns"

if [[ ! -f "$GATE_FILE" ]]; then
    echo "ERROR: .gate-patterns not found at $GATE_FILE"
    exit 1
fi

# Collect publishable files (everything cargo would pack)
FILES=$(find "$REPO_DIR" \
    -not -path '*/target/*' \
    -not -path '*/.git/*' \
    -not -name '.gate-patterns' \
    -not -name '.gitignore' \
    -type f \( -name '*.rs' -o -name '*.md' -o -name '*.toml' \))

LEAKS=0

while IFS=$'\t' read -r category pattern description; do
    # Skip comments and blank lines
    [[ "$category" =~ ^#.*$ || -z "$category" ]] && continue

    HITS=$(grep -Pn "$pattern" $FILES 2>/dev/null || true)
    if [[ -n "$HITS" ]]; then
        echo "BLOCKED [$category] $description"
        echo "$HITS" | head -5
        echo ""
        LEAKS=$((LEAKS + 1))
    fi
done < "$GATE_FILE"

if [[ $LEAKS -gt 0 ]]; then
    echo "========================================="
    echo "PUBLISH BLOCKED: $LEAKS pattern(s) matched."
    echo "Fix the leaks above, then re-run."
    echo "========================================="
    exit 1
else
    echo "Gate PASSED. Zero leaks. Safe to publish."
    exit 0
fi
