#!/usr/bin/env bash
# Checks that the MSRV and crate version quoted across the repo's docs/config
# all agree with the values in Cargo.toml, which is treated as the source of
# truth. Run from the repo root: .github/scripts/check-versions.sh
set -euo pipefail

fail=0

check() {
  local label="$1" expected="$2" actual="$3"
  echo "$label: $actual"
  if [ "$actual" != "$expected" ]; then
    echo "::error::$label mismatch: expected '$expected' (from Cargo.toml), found '$actual'"
    fail=1
  fi
}

# --- MSRV ---
cargo_msrv=$(grep -m1 '^rust-version' Cargo.toml | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
echo "Cargo.toml rust-version: $cargo_msrv (source of truth)"

toolchain_msrv=$(tr -d ' \t\n' < rust-toolchain)
check "rust-toolchain file" "$cargo_msrv" "$toolchain_msrv"

contributing_msrv=$(grep -oE 'Rust [0-9]+\.[0-9]+\.[0-9]+' .github/CONTRIBUTING.md | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
check "CONTRIBUTING.md" "$cargo_msrv" "$contributing_msrv"

for v in $(grep -oE 'msrv-[0-9]+\.[0-9]+\.[0-9]+|MSRV [0-9]+\.[0-9]+\.[0-9]+' src/lib.rs | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | sort -u); do
  check "src/lib.rs MSRV badge" "$cargo_msrv" "$v"
done

for v in $(grep -oE 'rust-toolchain@[0-9]+\.[0-9]+\.[0-9]+' .github/workflows/ci.yml | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | sort -u); do
  check "ci.yml pinned toolchain" "$cargo_msrv" "$v"
done

# --- crate version ---
cargo_version=$(grep -m1 '^version' Cargo.toml | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
cargo_minor="${cargo_version%.*}"
echo "Cargo.toml version: $cargo_version (source of truth)"

lib_version=$(grep -oE 'sealed = "[0-9]+\.[0-9]+"' src/lib.rs | grep -oE '[0-9]+\.[0-9]+')
check "src/lib.rs dependency example (major.minor)" "$cargo_minor" "$lib_version"

exit $fail
