#!/usr/bin/env bash
# Pre-push hook: prevent commercial code from leaking to the community remote.
#
# Git calls pre-push with the remote name and URL as arguments,
# and feeds (local_ref local_sha remote_ref remote_sha) lines on stdin.

remote="$1"
url="$2"

# Only guard pushes to the community origin (DexterFromLab)
if ! echo "$url" | grep -qi "DexterFromLab"; then
  exit 0
fi

echo "[pre-push] Scanning commits for commercial code before push to community remote..."

COMMERCIAL_PATTERNS="agor-pro/|src/lib/commercial/"

while read -r local_ref local_sha remote_ref remote_sha; do
  # Skip delete pushes
  if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
    continue
  fi

  # For new branches, diff against remote HEAD; for updates, diff against remote_sha
  if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
    range="$local_sha"
  else
    range="$remote_sha..$local_sha"
  fi

  # Check file paths in the commits being pushed
  leaked_files=$(git diff --name-only "$range" 2>/dev/null | grep -E "$COMMERCIAL_PATTERNS" || true)

  if [ -n "$leaked_files" ]; then
    echo ""
    echo "=========================================="
    echo " PUSH BLOCKED: Commercial code detected!"
    echo "=========================================="
    echo ""
    echo "The following commercial files were found in commits being pushed:"
    echo "$leaked_files" | sed 's/^/  - /'
    echo ""
    echo "You are pushing to the community remote ($url)."
    echo "Commercial code must NOT be pushed to this remote."
    echo ""
    echo "To fix: remove commercial files from these commits or push to the commercial remote instead."
    echo "=========================================="
    exit 1
  fi
done

exit 0
