#!/bin/sh

if [ $# -ge 1 ]; then
  #optionally allow tagging from a specified branch rather than master/main
  check_branch="$1"
  shift
fi

DIRNAME="$(dirname "$0")"

# utility functions
. "$DIRNAME"/functions.sh

# src distribution is all lower case, and has underscores only
SRC_DISTRIBUTION_NAME="$(project_name | tr '[:upper:]' '[:lower:]' | tr '-' '_')"
# wheel name replaces dashes with underscores, but is not necessarily lower case
BDIST_NAME="$(project_name | tr '\- ' _)"

if [ -n "$check_branch" ] && ! branch_is "$check_branch"; then
  _cur_branch="$(git_current_branch)"
  quit "Attempting to tag from branch $_cur_branch, not $check_branch. Check out $check_branch first." 1
fi

if [ -z "$check_branch" ] && ! branch_is_master_or_main; then
  quit "Checkout branch 'master' before generating release." 1
fi

if ! branch_is_clean; then
  echo "Tree contains uncommitted modifications:"
  git ls-files -m
  quit 1
fi
version=$(current_version)

if ! version_is_tagged "$version"; then
  echo "Current version $version isn't tagged."
  echo "Attempting to tag..."
  if [ -n "$check_branch" ]; then
    "$DIRNAME"/tag "$check_branch" || quit "Failed to tag a release." 1
  else
    "$DIRNAME"/tag || quit "Failed to tag a release." 1
  fi
fi

generate_dist() {
  python3 -m build || quit "Failed to generate source & binary distributions." 1
}

# if TWINE_UPLOAD_ENABLED was set in project_settings.sh, it must be set to "1"
if [ -z "$TWINE_UPLOAD_ENABLED" ] || [ "$TWINE_UPLOAD_ENABLED" = "1" ]; then
  version=$(current_version)

  generate_dist
  echo "About to post the following distribution files to pypi.org."
  ls -1 dist/"$SRC_DISTRIBUTION_NAME"-"$version".tar.gz dist/"$BDIST_NAME"-"$version"-py*whl

  # shellcheck disable=SC2119
  if prompt_yes_no; then

    python3 -m twine upload -u "__token__" dist/"$SRC_DISTRIBUTION_NAME"-"$version".tar.gz dist/"$BDIST_NAME"-"$version"-py*whl
  fi
else
  echo "twine upload to PyPI not enabled. Skipping."
fi
