#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "${REPO_ROOT}"

VERSION_FILE="./version"

require_clean_worktree() {
  if ! git diff --quiet --ignore-submodules -- || ! git diff --cached --quiet --ignore-submodules --; then
    echo "[tag-release] working tree is not clean; commit or stash changes before tagging a release" >&2
    exit 1
  fi
}

require_clean_worktree

current_branch="$(git symbolic-ref --short -q HEAD || true)"
if [[ -n "${current_branch}" && "${current_branch}" != "main" ]]; then
  echo "[tag-release] checkout main before creating the release tag" >&2
  exit 1
fi

if [[ ! -f "${VERSION_FILE}" ]]; then
  echo "[tag-release] missing ${VERSION_FILE}" >&2
  exit 1
fi

release_version="$(tr -d '[:space:]' < "${VERSION_FILE}")"
if [[ -z "${release_version}" ]]; then
  echo "[tag-release] ${VERSION_FILE} is empty" >&2
  exit 1
fi

release_tag="v${release_version}"
if git rev-parse -q --verify "refs/tags/${release_tag}" >/dev/null; then
  echo "[tag-release] tag ${release_tag} already exists locally" >&2
  exit 1
fi

git tag -a "${release_tag}" -m "Release ${release_tag}"

echo "Created release tag ${release_tag} at $(git rev-parse --short HEAD)"
echo "Next step:"
echo "  git push origin ${release_tag}"
