#!/bin/bash

# Usage: s/version++ [patch|minor|major]
#
# Bumps Cargo.toml, refreshes CHANGELOG.md from git-cliff, and tags HEAD.
#
# Workflow: commit your feature first (with a conventional-commit message),
# THEN run this script. git-cliff reads committed history, so any uncommitted
# changes won't appear in the new CHANGELOG.md section.

# set -v  # Enable verbose mode
set -e  # Exit on error

# scripts may need to be made executable on some platforms before they can be run
# chmod +x s/<filename> is the command to do this on unixy systems

bump="patch"
if [[ -n "${1-}" ]]; then
  case "$1" in
    patch|minor|major)
      bump="$1"
      ;;
    *)
      echo "Usage: s/version++ [patch|minor|major]" >&2
      exit 1
      ;;
  esac
fi

cargo set-version --bump "$bump"

version="$(awk -F\" '/^version =/ {print $2; exit}' Cargo.toml)"
tag="v$version"
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
  echo "Tag $tag already exists." >&2
  exit 1
fi

# Refresh CHANGELOG.md if git-cliff is on PATH. Renders the in-progress
# section under the new version + date by passing --tag.
# Skip silently when git-cliff isn't installed - it's a release-day tool.
if command -v git-cliff >/dev/null 2>&1; then
  git-cliff --tag "$tag" -o CHANGELOG.md
  git add CHANGELOG.md
  echo "CHANGELOG.md refreshed for $tag"
else
  echo "git-cliff not installed; skipping CHANGELOG.md refresh" >&2
  echo "Install with: cargo install git-cliff --locked" >&2
fi

git tag "$tag"

