#!/bin/sh
# BeaverScan Pre-Commit Hook
#
# This hook runs BeaverScan security scanning on staged files before allowing a commit.
# It uses incremental scanning to only check changed files for fast feedback.
#
# Installation:
#   beaverscan install-hook pre-commit
#
# Or manually:
#   cp templates/git-hooks/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit

# Exit immediately if a command exits with a non-zero status
set -e

echo "🦫 BeaverScan Pre-Commit Hook"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Check if beaverscan is installed
if ! command -v beaverscan >/dev/null 2>&1; then
    echo "❌ Error: BeaverScan CLI is not installed"
    echo "   Install: npm install -g @beaverscan/cli"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 1
fi

# Check if we're in a git repository
if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "❌ Error: Not a git repository"
    exit 1
fi

echo "📝 Scanning staged files..."
echo ""

# Run BeaverScan on staged files only
# Uses incremental scanning with git-diff-mode=staged for maximum speed
if beaverscan scan . --incremental --git-diff-mode staged --cache 2>&1; then
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "✅ Security scan passed!"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 0
else
    EXIT_CODE=$?
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "❌ Security scan failed!"
    echo ""
    echo "Critical or high severity issues detected in staged files."
    echo ""
    echo "Options:"
    echo "  1. Fix the security issues and try again"
    echo "  2. Review the scan report above"
    echo "  3. Skip this hook with: git commit --no-verify (not recommended)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit $EXIT_CODE
fi
