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

if [[ $# -ne 1 ]]; then
  echo "usage: scripts/publish-prerelease ARTIFACT_DIRECTORY" >&2
  exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
artifact_dir="$(cd "$1" && pwd)"
version="$(
  uv run --no-project --with packaging==26.2 \
    python scripts/check_release.py --print-version
)"
uv run --no-project --with packaging==26.2 python - "$version" <<'PY'
import sys
from packaging.version import Version

version = Version(sys.argv[1])
if not version.is_prerelease:
    raise SystemExit(f"refusing local publication of stable version {version}")
PY
if [[ "${FOAMWIKI_PUBLISH_CONFIRM:-}" != "$version" ]]; then
  echo "set FOAMWIKI_PUBLISH_CONFIRM=$version to confirm this immutable upload" >&2
  exit 2
fi
if [[ -z "${PYPI_TOKEN:-}" ]]; then
  echo "PYPI_TOKEN is not set" >&2
  exit 2
fi

verify_args=(scripts/verify_artifacts.py "$artifact_dir" "$version")
if [[ "$(uname -s)" == "Linux" && "$(uname -m)" == "x86_64" ]]; then
  verify_args+=(
    --expected-platform "manylinux_2_17_x86_64"
    --expected-platform "macosx_10_12_x86_64"
    --expected-platform "macosx_11_0_arm64"
  )
fi
uv run --no-project --with packaging==26.2 \
  python "${verify_args[@]}"
uvx --from abi3audit==0.0.26 abi3audit "$artifact_dir"/*.whl
uvx --from twine==6.2.0 twine check --strict "$artifact_dir"/*
UV_PUBLISH_TOKEN="$PYPI_TOKEN" uv publish \
  --trusted-publishing never \
  --check-url https://pypi.org/simple/ \
  "$artifact_dir"/*
