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

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

VERSION_FILE="./version"
PUBSPEC_FILE="./frontend/pweb/pubspec.yaml"
if [[ ! -f "${PUBSPEC_FILE}" && -f "./frontend/pweb/pubspec.yml" ]]; then
  PUBSPEC_FILE="./frontend/pweb/pubspec.yml"
fi

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

require_clean_worktree

"${REPO_ROOT}/ci/scripts/common/bump_version.sh"

new_version="$(tr -d '[:space:]' < "${VERSION_FILE}")"
release_tag="v${new_version}"

git add "${VERSION_FILE}" "${PUBSPEC_FILE}"
git commit -m "chore: prepare release ${release_tag}"

echo
echo "Prepared release commit for ${release_tag}"
echo "Next steps:"
echo "  1. push this branch and open a PR"
echo "  2. merge the PR to main"
echo "  3. verify the dev deployment from main"
echo "  4. checkout main and run ./ci/scripts/common/tag_release.sh"
