#!/usr/bin/env bash
set -euo pipefail

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

tag="${1:-${RELEASE_TAG:-}}"
if [ -z "$tag" ]; then
  echo "usage: scripts/ci/release-check vX.Y.Z" >&2
  exit 1
fi

version="${tag#v}"
if [ "$version" = "$tag" ]; then
  echo "expected v-prefixed tag, got: $tag" >&2
  exit 1
fi

PYTHON_BIN="${PYTHON_BIN:-python3}"
export PYTHON_BIN SETUPTOOLS_SCM_PRETEND_VERSION="$version"

scripts/ci/check

"$PYTHON_BIN" - <<'PY'
import glob
import os
import re

version = os.environ["SETUPTOOLS_SCM_PRETEND_VERSION"]
files = glob.glob("dist/*.whl") + glob.glob("dist/*.tar.gz")
if not files:
    raise SystemExit("no built distributions found")
pat = re.compile(r"-" + re.escape(version) + r"([.-])")
bad = [f for f in files if not pat.search(os.path.basename(f))]
if bad:
    raise SystemExit("version mismatch in built artifacts: " + ", ".join(bad))
PY
