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

pip install twine

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

if [ $# -ge 1 ] && [ -n "$1" ]; then
    api_file_path=$1
else
    echo "A valid spec file path needs to be specified"
    exit 1
fi

# check if api.spec file exists
test -f "$api_file_path" && echo "$api_file_path exists"

# resolve project base dir
project_base_dir=$(dirname $(dirname $api_file_path))
openapi_file_name=$(basename $api_file_path)

# resolve service version
pip install shyaml
version=$(cat $api_file_path | shyaml get-value info.version)
project_name=$(cat $api_file_path | shyaml get-value info.title)
echo "using version: $version and project name: $project_name"

client_project_name="${project_name}_client"

# create qualifier
qualifier=""
echo "${PWD}"
git_sha=$(git rev-parse HEAD)
git_tag=$(git tag --points-at "${git_sha}")

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")

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=""
else
    qualifier=".dev${build_number}"
fi

# make temp folder for codegen
temp_dir="$(mktemp -d)"
cp $api_file_path $temp_dir
cd $temp_dir
pwd

# codegen
client_lib_version="${version}${qualifier}"
docker run --rm -v ${temp_dir}:/local openapitools/openapi-generator-cli generate -i /local/${openapi_file_name} \
    -g python --package-name ${client_project_name} -p packageVersion=${client_lib_version} -o /local/
echo "created client project under ${temp_dir}"

# make the build
python setup.py sdist
python setup.py bdist_wheel

# upload to pipy server
twine_extra_args="--skip-existing"
twine upload dist/* --repository-url "${pypi_repo_url}" --username "${pypi_username}" --password "${pypi_password}" ${twine_extra_args}

rm -r $temp_dir
