#!/usr/bin/env bash
#
# Bump the release version state in ./VERSION.
#
#   scripts/bump-version.sh [build|patch|minor|major]
#
# Always increments the build number (CFBundleVersion) by 1. The argument additionally bumps a
# semver component of the marketing version (CFBundleShortVersionString), resetting lower ones.
# Default is minor (we're pre-1.0: each release is a minor, major stays 0 until BUMP=major):
#
#   minor (default)  bump minor, reset patch       0.1.3 (827) -> 0.2.0 (828)
#   major            bump major, reset minor+patch 0.4.2 (827) -> 1.0.0 (828)
#   patch            bump patch                    0.1.0 (827) -> 0.1.1 (828)
#   build            build number only             0.1.0 (827) -> 0.1.0 (828)
#
# Rewrites ./VERSION and prints "<marketing> <build>" (the new values) to stdout, so callers can
# capture them. Normally invoked by scripts/release-macos.sh; safe to run by hand to pre-bump.

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
FILE="$ROOT/VERSION"
KIND="${1:-minor}"

# Defaults so a missing/partial VERSION file still works (fresh checkout).
NUCLEIC_MARKETING_VERSION=0.1.0
NUCLEIC_BUILD_NUMBER=0
# shellcheck source=/dev/null
[ -f "$FILE" ] && . "$FILE"

IFS=. read -r MAJOR MINOR PATCH <<<"$NUCLEIC_MARKETING_VERSION"
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0}

case "$KIND" in
  major)        MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;;
  minor)        MINOR=$((MINOR + 1)); PATCH=0 ;;
  patch)        PATCH=$((PATCH + 1)) ;;
  build|"")     : ;;  # build number only (bumped unconditionally below)
  *) echo "bump-version: unknown bump '$KIND' (want: build|patch|minor|major)" >&2; exit 2 ;;
esac

NEW_VERSION="$MAJOR.$MINOR.$PATCH"
NEW_BUILD=$((NUCLEIC_BUILD_NUMBER + 1))

cat > "$FILE" <<EOF
# Nucleic release version state — the single source of truth for the app version.
# Bumped by scripts/release-macos.sh on every release; read by scripts/package-app.sh.
# Shell-sourceable (KEY=value). Don't hand-edit during a release — bump with:
#   make release-beta                 # 0.1.0 -> 0.2.0 (minor — the default), build +1
#   make release-beta BUMP=major      # 0.1.0 -> 1.0.0, build +1
#   make release-beta BUMP=patch      # 0.1.0 -> 0.1.1, build +1
#   make release-beta BUMP=build      # 0.1.0 -> 0.1.0 (build number only), build +1
#
#   NUCLEIC_MARKETING_VERSION  semantic version -> CFBundleShortVersionString
#   NUCLEIC_BUILD_NUMBER       monotonic build  -> CFBundleVersion (always +1 per release)
NUCLEIC_MARKETING_VERSION=$NEW_VERSION
NUCLEIC_BUILD_NUMBER=$NEW_BUILD
EOF

echo "$NEW_VERSION $NEW_BUILD"
