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

repo="${1:-pypi}"
tag="${2:-${RELEASE_TAG:-}}"
scripts/release/build "$repo" "$tag"

case "$repo" in
  pypi) repo_url="${TWINE_REPOSITORY_URL:-}" ;;
  testpypi) repo_url="${TWINE_REPOSITORY_URL:-https://test.pypi.org/legacy/}" ;;
  *) echo "unknown repository: $repo" >&2; exit 1 ;;
esac

args=()
if [ -n "$repo_url" ]; then
  args+=(--repository-url "$repo_url")
fi

shopt -s nullglob
artifacts=(artifacts/release/"$repo"/*.whl artifacts/release/"$repo"/*.tar.gz)
shopt -u nullglob
if [ ${#artifacts[@]} -eq 0 ]; then
  echo "no release artifacts found under artifacts/release/$repo" >&2
  exit 1
fi

python3 -m pip install --upgrade twine
python3 -m twine upload "${args[@]}" "${artifacts[@]}"
