#!/usr/bin/env bash
# Map a git tag or the Cargo.toml version to a package version X.Y.Z.
# Tags may be vX.Y.Z or X.Y.Z. Other spellings fail instead of being rewritten.
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

if [[ -n "${PACKAGE_VERSION:-}" ]]; then
  version="$PACKAGE_VERSION"
elif [[ -n "${CI_COMMIT_TAG:-}" ]]; then
  version="${CI_COMMIT_TAG#v}"
else
  version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$root/Cargo.toml" | head -n 1)"
fi

if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "package version must be X.Y.Z (tag vX.Y.Z or X.Y.Z); got '${CI_COMMIT_TAG:-$version}'" >&2
  exit 1
fi

printf '%s\n' "$version"
