#!/usr/bin/env bash
# Auto-bump patch version in Cargo.toml when .rs files are committed.
# Humans bump minor versions manually for releases.
set -euo pipefail

STAGED=$(git diff --cached --name-only --diff-filter=d)
[[ -z "$STAGED" ]] && exit 0
[[ ! -f Cargo.toml ]] && exit 0

# Only bump if Rust source files are staged
if ! echo "$STAGED" | grep -q '\.rs$'; then
    exit 0
fi

# Extract current version
CURRENT=$(sed -n 's/^version *= *"\(.*\)"/\1/p' Cargo.toml | head -1)
[[ -z "$CURRENT" ]] && exit 0

# Parse semver components
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT"
PATCH=$((PATCH + 1))
NEW="${MAJOR}.${MINOR}.${PATCH}"

# Replace first version line in Cargo.toml (macOS-compatible sed)
sed -i '' "s/^version = \"${CURRENT}\"/version = \"${NEW}\"/" Cargo.toml

# Update Cargo.lock if tracked
if git ls-files --error-unmatch Cargo.lock &>/dev/null; then
    cargo generate-lockfile --quiet 2>/dev/null || true
    git add Cargo.lock
fi

git add Cargo.toml
echo "[version-bump] ${CURRENT} -> ${NEW}"
