#!/usr/bin/env bash
# pre-push: block push if content-guard finds public-leak violations.
#
# Installed by `brigade init`. Activate once with:
#   git config core.hooksPath hooks
#
# Bypass only if you know what you are allowing through:
#   git push --no-verify
#
# Uses Brigade's embedded content guard. CONTENT_GUARD_DIR is an explicit
# compatibility override for an older standalone checkout.
set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
rc=0
if [[ -n "${CONTENT_GUARD_DIR:-}" ]]; then
  POLICY="${CONTENT_GUARD_POLICY:-$CONTENT_GUARD_DIR/policies/public-repo.json}"
  if [[ ! -d "$CONTENT_GUARD_DIR" ]]; then
    echo "pre-push: CONTENT_GUARD_DIR not found: $CONTENT_GUARD_DIR" >&2
    exit 1
  fi
  if [[ ! -f "$POLICY" ]]; then
    echo "pre-push: policy file not found: $POLICY" >&2
    exit 1
  fi
  echo "pre-push: scanning $REPO_ROOT with explicit content-guard compatibility override"
  PYTHONPATH="$CONTENT_GUARD_DIR/src" python3 -m content_guard scan "$REPO_ROOT" --policy "$POLICY" || rc=$?
else
  POLICY="${CONTENT_GUARD_POLICY:-public-repo}"
  if ! command -v brigade >/dev/null 2>&1; then
    echo "pre-push: brigade not found; reinstall brigade-cli to restore the embedded guard" >&2
    exit 1
  fi
  echo "pre-push: scanning $REPO_ROOT with Brigade's embedded guard"
  brigade scrub --target "$REPO_ROOT" --policy "$POLICY" --no-receipt || rc=$?
fi

if [[ "$rc" -eq 0 ]]; then
  exit 0
fi

if [[ "$rc" -eq 1 ]]; then
  echo >&2
  echo "pre-push: BLOCKED. content-guard found violations." >&2
  echo "pre-push: fix the leak, or add an inline allow-tag on the offending line:" >&2
  echo "pre-push:   <!-- content-guard: allow <rule-id> -->" >&2
  exit 1
fi

# Any other exit code is the scanner failing to run (missing deps, bad policy,
# crash), not a leak verdict. Do not mislabel it as found violations.
echo >&2
echo "pre-push: content-guard failed to run (exit code $rc); this is a scanner error, not a leak verdict." >&2
echo "pre-push: re-run it directly to see the error, then push again once the scanner works." >&2
exit 1
