#!/usr/bin/env bash
set -euo pipefail

fail=0

# Block pushing with active `[patch.*]` overrides in any tracked Cargo.toml.
while IFS= read -r file; do
  # Note: POSIX ERE escaping: `\[` matches literal `[`. Using `\\[` makes the
  # regex invalid on macOS/BSD grep ("brackets ([ ]) not balanced").
  if grep -nE '^[[:space:]]*\[patch\.' "$file" >/dev/null; then
    echo "ERROR: [patch.*] sections found in $file:" >&2
    grep -nE '^[[:space:]]*\[patch\.' "$file" >&2 || true
    fail=1
  fi
done < <(git ls-files '*Cargo.toml')

if [ "$fail" -ne 0 ]; then
  echo "Fix: comment out or remove [patch.*] sections before pushing, and publish patched deps upstream first." >&2
  exit 1
fi

echo "pre-push: running tests..."
cargo test --all-features --quiet

echo "pre-push: all checks passed"
