#!/usr/bin/env bash
# Computes the marketing version (CFBundleShortVersionString) from git tags and
# prints it on one line, e.g. "0.2.0". Requires full history + tags
# (fetch-depth: 0 + `git fetch --tags` in CI); a shallow clone silently
# collapses to the bootstrap fallback and produces the wrong number.
#
# The version is a pure function of the nearest reachable v* tag and how many
# commits HEAD is past it ("distance"):
#
#   distance 0 (HEAD on a tag)   -> the tag verbatim   (a freshly-cut
#                                                        major/hotfix build)
#   distance >=1 on main         -> last release + minor, patch reset to 0
#   distance >=1 on release/*    -> last release + patch (a hotfix branch)
#
# The major-vs-minor-vs-patch *decision* lives in the release workflow; this
# script only knows the mechanical default (+minor) and "trust the tag when we
# are sitting on one". Set VERSION_BRANCH to override branch detection (CI
# checks out a detached HEAD, so `git rev-parse --abbrev-ref` returns "HEAD").
set -euo pipefail

BRANCH="${VERSION_BRANCH:-$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo main)}"

# --match keeps only vN* tags; --exclude drops pre-release/test tags with a dash
# (e.g. v0.0.1-test) so they can never become the base version.
DESC=$(git describe --tags --long --match 'v[0-9]*' --exclude '*-*' 2>/dev/null \
  || echo "v0.0.0-1-g0000000")

TAG=${DESC%-*-g*}          # v0.1.0-170-ga02486f -> v0.1.0
DIST=${DESC#"$TAG"-}       # -> 170-ga02486f
DIST=${DIST%-g*}           # -> 170
BASE=$(printf '%s' "${TAG#v}" | sed -E 's/[^0-9.]//g')
IFS='.' read -r MA MI PA <<< "$BASE"
MA=${MA:-0}; MI=${MI:-0}; PA=${PA:-0}

if   [[ "$DIST" -eq 0 ]];          then VERSION="${MA}.${MI}.${PA}"
elif [[ "$BRANCH" == release/* ]]; then VERSION="${MA}.${MI}.$((PA + 1))"
else                                    VERSION="${MA}.$((MI + 1)).0"
fi

[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] \
  || { echo "derive-version: invalid '$VERSION' (from '$DESC')" >&2; exit 1; }

printf '%s\n' "$VERSION"
