#!/usr/bin/env bash
# Print the package version from Cargo.toml.
#
# Cargo.toml is the single source of truth for PAC's version. maturin reads
# it directly when building wheels; pyproject.toml does not duplicate it.
#
# Output: bare version string with no trailing newline manipulation.
# Example: 0.3.0-alpha.16

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cargo_toml="${repo_root}/Cargo.toml"

if [[ ! -f "${cargo_toml}" ]]; then
    echo "error: ${cargo_toml} not found" >&2
    exit 1
fi

# Match the first `version = "..."` inside the [package] table only.
# awk state machine: enter [package], grab first version line, exit.
version="$(awk '
    /^\[package\]/      { in_pkg = 1; next }
    /^\[/ && in_pkg     { exit }
    in_pkg && /^version[[:space:]]*=/ {
        match($0, /"[^"]+"/)
        print substr($0, RSTART + 1, RLENGTH - 2)
        exit
    }
' "${cargo_toml}")"

if [[ -z "${version}" ]]; then
    echo "error: no [package] version found in ${cargo_toml}" >&2
    exit 1
fi

printf '%s\n' "${version}"
