#!/usr/bin/env bash
# git-bump-version: bump VERSION file, commit, and tag release
# Usage: git-bump-version [new_version] [repo_path]
#
# If new_version is omitted, it auto-increments the last component:
#   1.2.0 -> 1.2.1
#   0.9.3 -> 0.9.4
#
# Defaults:
#   repo_path = DEFAPP env var or "defapp"
#
# Example:
#   git-bump-version
#   git-bump-version 1.3.0
#   git-bump-version 1.3.0 ./app1

set -euo pipefail

NEW_VERSION="${1:-}"
REPO_PATH="${2:-}"
DEFAPP="${DEFAPP:-defapp}"

if [[ -n "$REPO_PATH" ]]; then
    if [[ ! -d "$REPO_PATH" ]]; then
        echo "Error: directory not found: $REPO_PATH" >&2
        exit 1
    fi
    cd "$REPO_PATH"
elif [[ -d "$DEFAPP" ]]; then
    cd "$DEFAPP"
else
    echo "Error: no repo directory found (DEFAPP or default 'defapp')" >&2
    exit 1
fi

VERSION_FILE="VERSION"

# Determine new version
if [[ -z "$NEW_VERSION" ]]; then
    if [[ -f "$VERSION_FILE" ]]; then
        CURRENT_VERSION=$(cat "$VERSION_FILE" | tr -d '[:space:]')
        if [[ ! "$CURRENT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Error: existing VERSION does not look like semver (X.Y.Z): '$CURRENT_VERSION'" >&2
            exit 1
        fi
        # Increment patch
        IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
        PATCH=$((PATCH + 1))
        NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
    else
        # Start from 0.0.1 if no VERSION file
        NEW_VERSION="0.0.1"
    fi
fi

# Write VERSION file
echo "$NEW_VERSION" > "$VERSION_FILE"

# Commit
git add "$VERSION_FILE"
git commit -m "Bump version to $NEW_VERSION" || {
    echo "Warning: nothing to commit or commit failed; continuing to tag." >&2
}

# Create tag
TAG_NAME="v$NEW_VERSION"
if git rev-parse "$TAG_NAME" >/dev/null 2>&1; then
    echo "Warning: tag $TAG_NAME already exists. Skipping tag creation." >&2
else
    git tag -a "$TAG_NAME" -m "Release $TAG_NAME"
fi

echo "Version bumped to $NEW_VERSION (tag: $TAG_NAME)"
