#!/bin/bash
#
# Git pre-commit hook for Himmelblau
#
# This hook runs SELinux policy tests when changes are made to the policy file.
#
# To install this hook, run from the repository root:
#   cp scripts/hooks/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# Or use: make install-hooks

set -e

# Get the repository root directory
REPO_ROOT="$(git rev-parse --show-toplevel)"

# Check if any staged files match the SELinux policy files
SELINUX_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^src/selinux/src/himmelblaud\.(te|fc)$' || true)

if [ -n "$SELINUX_FILES" ]; then
    echo "SELinux policy files changed:"
    echo "$SELINUX_FILES"
    echo ""
    echo "Running SELinux policy tests..."
    echo ""

    # Run the SELinux test
    if ! make -C "$REPO_ROOT" test-selinux; then
        echo ""
        echo "ERROR: SELinux policy test failed!"
        echo ""
        echo "Please fix the policy issues before committing."
        echo "You can run 'make test-selinux' to see detailed output."
        echo ""
        echo "To bypass this check (not recommended), use: git commit --no-verify"
        exit 1
    fi

    echo ""
    echo "SELinux policy tests passed."
fi

exit 0
