#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2026 Marcus Baw and Baw Medical Ltd
# SPDX-License-Identifier: AGPL-3.0-or-later

set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

CARGO_TOML="Cargo.toml"

usage() {
  echo "Usage: s/version++ [patch|minor|major]" >&2
}

if [[ $# -gt 1 ]]; then
  usage
  exit 2
fi

bump="${1:-patch}"
case "$bump" in
  patch|minor|major) ;;
  *)
    usage
    echo "Invalid bump: $bump" >&2
    exit 2
    ;;
esac

# Read current version
current=$(grep -E '^version\s*=' "$CARGO_TOML" | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "Current version: $current"

# Parse semver parts
IFS='.' read -r major minor patch <<< "$current"
if [[ ! "$major" =~ ^[0-9]+$ || ! "$minor" =~ ^[0-9]+$ || ! "$patch" =~ ^[0-9]+$ ]]; then
  echo "Cannot bump non-simple SemVer version: $current" >&2
  exit 1
fi

case "$bump" in
  major)
    next="$((major + 1)).0.0"
    ;;
  minor)
    next="${major}.$((minor + 1)).0"
    ;;
  patch)
    next="${major}.${minor}.$((patch + 1))"
    ;;
esac

echo "Bumping $bump: $current -> $next"

# Update Cargo.toml
sed -i "0,/^version\s*=/{s/^version\s*=\s*\"${current}\"/version = \"${next}\"/}" "$CARGO_TOML"

# Regenerate Cargo.lock
cargo generate-lockfile --manifest-path "$CARGO_TOML"

# Commit
git add "$CARGO_TOML" Cargo.lock
git commit -m "bump version to ${next}"

# Push. The auto-tag GitHub Actions workflow (.github/workflows/auto-tag.yml)
# detects the Cargo.toml change on main, creates the matching v<version>
# tag, and invokes release.yml. Tagging used to happen here; do not re-add
# it - a local tag plus the CI-created tag would race and produce noisy
# duplicate-tag failures on push.
git push

echo "Pushed bump to ${next}. CI will create the v${next} tag and release."
