#!/bin/bash
set -euo pipefail

###
#
# Publishes all *.whl files to PyPI
#
# Usage: ./publib-pypi [DIR]
#
# DIR is where *.whl files are looked up (default is "dist/python")
#
# TWINE_USERNAME (optional, ignored when using Trusted Publishers)
# TWINE_PASSWORD (optional, ignored when using Trusted Publishers)
# PYPI_TRUSTED_PUBLISHER (optional) - set to any value to use Trusted Publisher authentication
# PYPI_DISABLE_ATTESTATIONS (optional) - set to any value to disable attestations
#
###

cd "${1:-"dist/python"}"

# Evaluate trusted publisher flag once as boolean
use_trusted_publisher=false
if [ -n "${PYPI_TRUSTED_PUBLISHER:-}" ] && [ "${PYPI_TRUSTED_PUBLISHER}" != "false" ]; then
  use_trusted_publisher=true
fi

if [ -z "$(ls *.whl)" ]; then
  echo "cannot find any .whl files in $PWD"
  exit 1
fi

# Validate credentials before installing packages
if [ "$use_trusted_publisher" = "false" ]; then
  [ -z "${TWINE_USERNAME:-}" ] && {
    echo "Missing TWINE_USERNAME (required when not using Trusted Publishers)"
    exit 1
  }
  
  [ -z "${TWINE_PASSWORD:-}" ] && {
    echo "Missing TWINE_PASSWORD (required when not using Trusted Publishers)"
    exit 1
  }
fi

# Basic upload command options
upload_opts="--verbose --skip-existing"

# Install required packages
packages="twine<6.2.0"
if [ "$use_trusted_publisher" = "true" ]; then
  packages="$packages id"

  if [ -z "${PYPI_DISABLE_ATTESTATIONS:-}" ]; then
    # add attestations package
    packages="$packages pypi-attestations"
    # add attestations opt to upload command 
    upload_opts="$upload_opts --attestations"
  fi
fi
python3 -m pip install --user --upgrade $packages

# Check for Trusted Publisher
if [ "$use_trusted_publisher" = "true" ]; then
  echo "Using PyPI Trusted Publisher authentication"
  
  # Determine audience based on repository
  audience="pypi"
  mint_url="https://pypi.org/_/oidc/mint-token"
  if [ "${TWINE_REPOSITORY:-}" = "testpypi" ]; then
    audience="testpypi"
    mint_url="https://test.pypi.org/_/oidc/mint-token"
  fi
  
  # Generate OIDC token and mint API token
  oidc_token=$(python3 -m id "$audience")
  resp=$(curl -s -X POST "$mint_url" -d "{\"token\": \"${oidc_token}\"}")
  api_token=$(jq -r '.token' <<< "${resp}")
  
  export TWINE_USERNAME="__token__"
  export TWINE_PASSWORD="$api_token"

  if [ -z "${PYPI_DISABLE_ATTESTATIONS:-}" ]; then
    echo "Signing packages with pypi-attestations"
    python3 -m pypi_attestations sign *
  fi
fi

# Check for dry run
if [ "${PUBLIB_DRYRUN:-}" = "true" ]; then
  echo "🏜️ Dry run: skipping PyPI upload"
  for file in *.whl; do
    echo "  (would upload ${file})"
  done
  echo "SUCCESS (dry run)"
  exit 0
fi

echo "Uploading packages to PyPI"
python3 -m twine upload $upload_opts *
