#!/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=${ZOOX_BRANCH_NAME:-""}
if [[ -z "${current_git_branch}" ]]; then
    current_git_branch=$(git rev-parse --abbrev-ref HEAD)
fi
current_git_branch=$(echo "${current_git_branch}" | sed "s|/|_|g" | sed "s|--*|-|g")

build_number=$(date +%s)
# If the git sha has tags associated with it then publish the version as released (empty qualifier) and also add skip
# flags to avoid build failures due to publish errors during repeated builds in CI (as the released package may already
# exist from a previous build). If the branch is master and has no tags then mark the package as dev build otherwise
# it must be a non master branch so mark the build with branch name.
if [[ "${git_tag}" =~ "${project_name}__" ]]; then
    qualifier=""
elif [[ "${current_git_branch}" == "master" ]]; then
    qualifier=".dev${build_number}"
else
    qualifier=".${current_git_branch}${build_number}"
fi

# Copy everything into a temp directory so that we're not directly modifying source.
temp_build_dir=$(mktemp --directory)
cp -R . $temp_build_dir
# Create an environment variable for the git root before changing directory
# to the temp dir, so that the setuptools can know where is the git root
export CI_PYTHON_GIT_ROOT=$(git rev-parse --show-toplevel)
cd $temp_build_dir

# Remove the old build and dist folder
rm -rf build dist

# 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}"

# Upload the package if the branch is not HEAD or qualifier is empty
if [[ "${current_git_branch}" != "HEAD" || -z "${qualifier}" ]]; then
    twine upload dist/* --repository-url "${pypi_repo_url}"  --username "${pypi_username}" --password "${pypi_password}" ${twine_extra_args}
fi
