#!/usr/bin/env bash
# Git pre-commit hook to automatically bump the patch version in VERSION file.
# It only increments the version if files other than VERSION are staged for commit.

set -euo pipefail

VERSION_FILE="VERSION"

if [ ! -f "$VERSION_FILE" ]; then
    echo "1.0.0" > "$VERSION_FILE"
    git add "$VERSION_FILE"
    exit 0
fi

# Check if there are staged changes other than VERSION, documentation (*.md), or installers folder
if ! git diff --cached --name-only | grep -Ev "^($VERSION_FILE$|.*\.md$|^installers/)" | grep -q .; then
    # No other files staged, skip version bump
    exit 0
fi

# Read current version
current_version=$(cat "$VERSION_FILE" | tr -d '[:space:]')

# Basic regex validation for semantic versioning (X.Y.Z)
if [[ ! "$current_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Error: Current version '$current_version' in $VERSION_FILE is not in X.Y.Z format." >&2
    exit 1
fi

# Parse version components
IFS='.' read -r major minor patch <<< "$current_version"

# Increment patch version
patch=$((patch + 1))
new_version="$major.$minor.$patch"

# Write to VERSION file
echo "$new_version" > "$VERSION_FILE"

# Add VERSION file to the commit
git add "$VERSION_FILE"

echo "[pre-commit] Automatically bumped version from $current_version to $new_version"
