#!/usr/bin/env bash

set -e

production=${1:-no}

if [[ -d venv ]]
then
  source venv/bin/activate
fi

# Get the new version
new_version=$(python -m setuptools_scm)

if [[ ! "$new_version" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]+\.?\d?\e?\v?[0-9]?$ ]] && [[ "$production" != "production" ]]
then
  >&2 echo "The release version must be a semver string with optional suffix '.devX' specified by a Git tag on some past commit. Currently found ${new_version}."
  exit 1
elif [[ ! "$new_version" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]+$ ]] && [[ "$production" = "production" ]]
then
  >&2 echo "The release version must be a semver string specified by a Git tag on the current commit. Currently found ${new_version}. Most likely resolution is to commit/remove all pending changes in the repository, then issue the \`git tag\` command before running this script."
  exit 1
fi

python -m build

if [[ "$production" = "production" ]]
then
  options=
else
  options="-r testpypi"
fi
twine upload $options dist/artefacts_cli-${new_version}-py3-none-any.whl
