#!/usr/bin/env bash
# Usage:
#   scripts/release/bump.sh              bump by branch prefix (fix/*, feat/*, ...), falling back to commit types
#   scripts/release/bump.sh patch|minor|major
#   scripts/release/bump.sh X.Y.Z        set an explicit version
#   scripts/release/bump.sh --dry-run    print the next version and exit
#
# Run on a PR branch after its commits are made. The next version is derived from the latest
# vX.Y.Z tag (not package.json), so re-running after a rebase is safe. Updates package.json and
# CHANGELOG.md; commit them with the PR. Merging to main tags the version via release-tag.yml.
set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

dry_run=false
arg=""
for a in "$@"; do
  case "$a" in
    --dry-run) dry_run=true ;;
    *) arg="$a" ;;
  esac
done

git fetch --tags --quiet origin 2>/dev/null || true
last_tag=$(git describe --tags --match 'v[0-9]*' --abbrev=0 2>/dev/null || true)
[ -n "$last_tag" ] || { echo "No vX.Y.Z tag found; run 'git fetch --tags'" >&2; exit 1; }
IFS=. read -r maj min pat <<<"${last_tag#v}"

bump() {
  case "$1" in
    major) echo "$((maj + 1)).0.0" ;;
    minor) echo "${maj}.$((min + 1)).0" ;;
    patch) echo "${maj}.${min}.$((pat + 1))" ;;
  esac
}

branch=$(git rev-parse --abbrev-ref HEAD)
case "$arg" in
  "")
    case "$branch" in
      major/* | release/major/*) level=major ;;
      feat/* | feature/*) level=minor ;;
      fix/* | hotfix/* | chore/* | docs/* | refactor/* | test/* | build/* | ci/* | perf/* | style/* | revert/*) level=patch ;;
      *) level="" ;;
    esac
    if [ -n "$level" ]; then
      next=$(bump "$level")
    else
      next=$(scripts/release/changelog.sh suggest)
    fi
    ;;
  patch | minor | major) next=$(bump "$arg") ;;
  *)
    [[ "$arg" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "argument must be patch, minor, major or X.Y.Z" >&2; exit 2; }
    next="$arg"
    ;;
esac

echo "${last_tag} -> v${next} (branch: ${branch})"
$dry_run && exit 0

if git rev-parse -q --verify "refs/tags/v${next}" >/dev/null; then
  echo "Tag v${next} already exists" >&2
  exit 1
fi

npm pkg set version="$next"
scripts/release/changelog.sh generate "$next"
echo "Updated package.json and CHANGELOG.md. Commit them with this PR."
