#!/usr/bin/env bash
# pre-push hook: block pushing on common mistakes.
#
# 1. Checks for untracked source files in tracked directories, which likely
#    need to be committed or removed before the pushed code will build.
# 2. Runs `make check-format` to verify formatting.
#
# Automatically active via `make all` / `make check` (sets core.hooksPath).
#
# Skip with:
#   git push --no-verify

set -e

# Only act when we have a terminal (skip in CI / automated pushes)
if [ ! -t 1 ] && [ -z "$ROCKSDB_FORMAT_HOOK" ]; then
  exit 0
fi

FAILED=0

# --- Check for untracked source files in tracked directories ---
SUSPECT_FILES=$(git ls-files --others --exclude-standard \
  | grep -E '\.(cc|cpp|c|h|hpp|java|py|mk|sh)$' \
  | grep -v '^third-party/' \
  | while IFS= read -r f; do
      top_dir="${f%%/*}"
      if [ "$top_dir" = "$f" ] || [ -n "$(git ls-files "$top_dir/" | head -1)" ]; then
        echo "$f"
      fi
    done)

if [ -n "$SUSPECT_FILES" ]; then
  echo ""
  echo "==========================================================="
  echo "  pre-push: untracked source files in tracked directories."
  echo "  Push blocked. These may need to be committed, or the"
  echo "  pushed code could fail to build:"
  echo ""
  echo "$SUSPECT_FILES" | sed 's/^/    /'
  echo ""
  echo "  Commit them, add to .gitignore, delete, or --no-verify."
  echo "==========================================================="
  FAILED=1
fi

# --- Check formatting ---
echo "pre-push: running format check..."

if ! make check-format; then
  echo ""
  echo "==========================================================="
  echo "  pre-push: formatting issues detected. Push blocked."
  echo "  Run 'make format-auto' then amend your commit and retry."
  echo "==========================================================="
  FAILED=1
else
  echo "pre-push: formatting is clean."
fi

exit $FAILED
