#!/usr/bin/env bash
# Cut a formal release: set VERSION (optional arg) and tag the current commit
# as v<VERSION>. A clean checkout on that tag makes deploy.sh stamp the formal
# "X.Y.Z" instead of a dev build.
#
#   ./release.sh          # tag v<current VERSION>
#   ./release.sh 0.1.0    # bump VERSION to 0.1.0, then tag v0.1.0
#
# Pushing the tag is left to you:  git push origin "v<VERSION>"
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"

if [[ $# -ge 1 ]]; then
  [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "error: version must be X.Y.Z (got '$1')" >&2; exit 1; }
  echo "$1" > VERSION
  git add VERSION
  git commit -m "Bump version to $1" >/dev/null
  echo "VERSION -> $1 (committed)"
fi

VER="$(cat VERSION)"
[[ -z "$(git status --porcelain)" ]] || { echo "error: working tree dirty — commit before releasing" >&2; exit 1; }

if git rev-parse -q --verify "refs/tags/v$VER" >/dev/null; then
  echo "error: tag v$VER already exists" >&2; exit 1
fi

git tag -a "v$VER" -m "Release v$VER"
echo "tagged v$VER"
echo "next:  git push origin v$VER   &&   ./deploy.sh   (will now stamp the formal v$VER)"
