#!/usr/bin/env bash
# git-bump-version: bump VERSION file, commit, and tag release
# Usage:
#   git-bump-version [new_version]
#   git-bump-version [new_version] [repo_path]
#
# If repo_path is omitted, uses the current directory.

set -euo pipefail

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

# If REPO_PATH not given, use DEFAPP or current dir
if [[ -z "$REPO_PATH" ]]; then
    if [[ -n "$DEFAPP" && -d "$DEFAPP" ]]; then
        REPO_PATH="$DEFAPP"
    else
        # Default: current directory
        REPO_PATH="."
    fi
fi

# Resolve to absolute path and cd
if [[ ! -d "$REPO_PATH" ]]; then
    echo "Error: directory not found: $REPO_PATH" >&2
    exit 1
fi
cd "$REPO_PATH"

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
        IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
        PATCH=$((PATCH + 1))
        NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
    else
        NEW_VERSION="0.0.1"
    fi
fi

echo "$NEW_VERSION" > "$VERSION_FILE"

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

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)"
