#!/bin/bash
# Pre-commit hook to update copyright headers

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

# Check if update_copyright.sh exists and is executable
if [ ! -x "$ROOT_DIR/scripts/update_copyright.sh" ]; then
    echo "Warning: scripts/update_copyright.sh not found or not executable"
    exit 1
fi

# Get list of staged C++ source files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(cpp|hpp|h|c|cc)$' || true)

if [ -z "$STAGED_FILES" ]; then
    # No C++ files staged, nothing to do
    exit 0
fi

echo "Updating copyright headers for staged files..."

# Update copyright for each staged file
updated=0
for file in $STAGED_FILES; do
    if [ -f "$ROOT_DIR/$file" ]; then
        # Run update_copyright.sh on the file
        if "$ROOT_DIR/scripts/update_copyright.sh" "$ROOT_DIR/$file" > /dev/null 2>&1; then
            # Re-stage the file if it was modified
            git add "$ROOT_DIR/$file"
            echo "  ✓ Updated: $file"
            ((updated++))
        fi
    fi
done

if [ $updated -gt 0 ]; then
    echo "Updated copyright headers in $updated file(s)"
else
    echo "No copyright headers needed updating"
fi

exit 0
