#!/usr/bin/env bash

set -euo pipefail

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

qualifier=""
twine_extra_args=""

git_sha=$(git rev-parse HEAD)
current_git_branch=${bamboo_repository_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")

git_tag=$(git tag --points-at "${git_sha}")
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}" =~ "mission_planner__" ]]; then
    qualifier=""
    twine_extra_args="--skip-existing"
elif [[ "${current_git_branch}" == "master" ]]; then
    qualifier=".dev${build_number}"
else
    qualifier=".${current_git_branch}${build_number}"
fi

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

# Update the qualifier
sed --in-place "s|__QUALIFIER__ = \".*\"|__QUALIFIER__ = \"${qualifier}\"|g" setup.py

# Copy the cpp build file
bash ./build_and_copy_planner_so.sh

# Make the build
tox

# 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
