#!/usr/bin/env bash
# pre-push hook: rejects pushing a version tag whose version
# does not match VERSION in finalcif/__init__.py.
#
# Activate with:
#   git config core.hooksPath .githooks

INIT_FILE="finalcif/__init__.py"

# Extract VERSION from source (pure shell, no Python dependency)
get_source_version() {
    grep -m1 '^VERSION' "$INIT_FILE" | sed 's/^VERSION[[:space:]]*=[[:space:]]*\([0-9]*\).*/\1/'
}

# Read stdin for refs being pushed
while read -r local_ref local_sha remote_ref remote_sha; do
    # Only check version tags (refs/tags/*)
    if [[ "$local_ref" == refs/tags/* ]]; then
        tag_version="${local_ref#refs/tags/}"
        tag_version="${tag_version#v}" # remove leading v if any

        # Only process if tag is an integer
        if [[ "$tag_version" =~ ^[0-9]+$ ]]; then
            source_version=$(get_source_version)
            if [ $? -ne 0 ] || [ -z "$source_version" ]; then
                echo "ERROR: Could not extract VERSION from ${INIT_FILE}" >&2
                exit 1
            fi
            if [ "$tag_version" != "$source_version" ]; then
                echo "ERROR: Tag ${tag_version} does not match VERSION = ${source_version} in ${INIT_FILE}" >&2
                echo "Update VERSION before tagging, or fix the tag name." >&2
                exit 1
            fi
        fi
    fi
done

exit 0

