#!/usr/bin/env bash

# Asserts that the version field in Cargo.toml matches the tag version string.
#
# Cargo version format:  0.10.0
# Tag version format:   v0.10.0
#
# Usage: './assert_cargo_version.sh v0.10.0'

set -euo pipefail

TAG_VERSION="$1"

if [[ ! "$TAG_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "!!! Tag version must be in the format vX.Y.Z (e.g., v0.10.0)"
  exit 1
fi

EXPECTED_VERSION="${TAG_VERSION#v}"

# Extract version from [workspace.package] block only
# This was generated by chatgpt
CARGO_VERSION=$(awk '
  $0 ~ /^\[workspace\.package\]/ { in_section=1; next }
  $0 ~ /^\[/ { in_section=0 }
  in_section && $1 == "version" { gsub(/"/, "", $3); print $3; exit }
' Cargo.toml)

if [[ -z "$CARGO_VERSION" ]]; then
  echo "!!! Could not find version in [workspace.package] section of Cargo.toml"
  exit 1
fi

if [[ "$CARGO_VERSION" != "$EXPECTED_VERSION" ]]; then
  echo "!!! Version mismatch!"
  echo "Tag version:     $TAG_VERSION"
  echo "Cargo.toml has:  $CARGO_VERSION"
  exit 1
else
  echo "Version matches: $CARGO_VERSION"
fi
