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

project_name=${ZOOX_PROJECT_NAME}

pypi_repo_url=${PYPI_REPOSITORY_URL:-"https://pypi.zooxlabs.com/pypi"}
pypi_index_url=${PYPI_INDEX_URL:-"https://pypi.zooxlabs.com/simple/"}
pypi_username=${PYPI_USERNAME:-zoox}
pypi_password=${PYPI_PASSWORD:-zoox}

qualifier=""
twine_extra_args="--skip-existing"

git_sha=$(git rev-parse HEAD)
git_tag=$(git tag --points-at "${git_sha}")

current_git_branch=$(git rev-parse --abbrev-ref HEAD)
current_git_branch=$(echo "${current_git_branch}" | sed "s|/|_|g" | sed "s|--*|-|g")

qualifier="-$git_sha"

# Update the qualifier
# First check that what we're going to update actually exists,
# otherwise we run the risk of not actually updating the qualifier
# and tox will build a unqualified (i.e. release!) version.
qualifier_match_string="^__QUALIFIER__ *= *[\"\'][\"\']$"
if ! grep --quiet "${qualifier_match_string}" setup.py; then
    echo "Invalid or missing __QUALIFIER__ set in setup.py"
    exit 1
fi
sed --in-place "s|${qualifier_match_string}|__QUALIFIER__ = \"${qualifier}\"|g" setup.py

# Make the build
tox -i "${pypi_index_url}"

twine upload dist/* --repository-url "${pypi_repo_url}"  --username "${pypi_username}" --password "${pypi_password}" ${twine_extra_args}
