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

if [[ $# -ne 1 ]]; then
  echo "usage: scripts/build-release FRESH_REPO_RELATIVE_OUTPUT_DIRECTORY" >&2
  exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "$repo_root"
output="$1"
if [[ "$output" = /* ]]; then
  echo "output directory must be relative to the repository" >&2
  exit 2
fi
output_absolute="$(
  uv run --no-project python - "$repo_root" "$output" <<'PY'
import sys
from pathlib import Path

print((Path(sys.argv[1]) / sys.argv[2]).resolve(strict=False))
PY
)"
if [[ "$output_absolute" != "$repo_root/"* ]]; then
  echo "output directory must remain inside the repository" >&2
  exit 2
fi
if [[ -e "$output_absolute" ]]; then
  echo "refusing to reuse artifact directory: $output_absolute" >&2
  exit 2
fi

version="$(
  uv run --no-project --with packaging==26.2 \
    python scripts/check_release.py --print-version
)"
mkdir -p "$output_absolute"
uvx --from maturin==1.14.1 maturin sdist --out "$output_absolute"

verify_platforms=()
if [[ "$(uname -s)" == "Linux" ]]; then
  case "$(uname -m)" in
    x86_64)
      target="x86_64-unknown-linux-gnu"
      verify_platforms=(
        "manylinux_2_17_x86_64"
        "macosx_10_12_x86_64"
        "macosx_11_0_arm64"
      )
      ;;
    aarch64|arm64)
      target="aarch64-unknown-linux-gnu"
      verify_platforms=("manylinux_2_17_aarch64")
      ;;
    *)
      echo "unsupported Linux architecture: $(uname -m)" >&2
      exit 2
      ;;
  esac
  docker run --rm \
    --workdir /io \
    --env "HOST_UID=$(id -u)" \
    --env "HOST_GID=$(id -g)" \
    --env "MATURIN_TARGET=$target" \
    --env "CARGO_TARGET_DIR=/tmp/foamwiki-target" \
    --volume "$repo_root:/io:ro" \
    --volume "$output_absolute:/output" \
    --entrypoint /bin/sh \
    ghcr.io/pyo3/maturin@sha256:2665227312dd1eab1c29c70a001dc8aac53155a2d048bede3b2df7f1691c8e38 \
    -c 'maturin build --release --locked --manylinux 2014 \
      --target "$MATURIN_TARGET" --out /output &&
      chown -R "$HOST_UID:$HOST_GID" /output'
  if [[ "$(uname -m)" == "x86_64" ]]; then
    scripts/build-macos-cross "$output_absolute"
  fi
else
  uvx --from maturin==1.14.1 maturin build \
    --release --locked --out "$output_absolute"
fi

verify_args=(scripts/verify_artifacts.py "$output_absolute" "$version")
for platform in "${verify_platforms[@]}"; do
  verify_args+=(--expected-platform "$platform")
done
uv run --no-project --with packaging==26.2 \
  python "${verify_args[@]}"
uvx --from abi3audit==0.0.26 abi3audit "$output_absolute"/*.whl
uvx --from twine==6.2.0 twine check --strict "$output_absolute"/*
uvx --from check-wheel-contents==0.6.3 check-wheel-contents "$output_absolute"/*.whl
uv publish --dry-run --trusted-publishing never "$output_absolute"/*
scripts/smoke-dist "$output_absolute" "$version"
echo "release artifacts are ready in $output_absolute"
