#!/usr/bin/env bash

# Configure shell.
set +x -e -u -o pipefail

# User-friendly print wrapper.
log() {
  printf '[%s] [%s] %s\n' "${0##*/}" "$( date '+%Y-%m-%dT%H:%M:%S' )" "${@}"
}

# ------------------------------------------------------------

# Configure SSH key for private Github repositories.
log 'Configuring SSH key'

chmod -R u=rX,go-rwx "${HOME}/.ssh"
export GIT_SSH_COMMAND="/usr/bin/ssh -i '${HOME}/.ssh/github' -l git -o StrictHostKeyChecking=no"

# ------------------------------------------------------------

log 'Launching PyPI package publisher'

cd "sources/${ROOT_DIRECTORY}" || (
  log "Error! Can't cd into ROOT_DIRECTORY: '${ROOT_DIRECTORY}'. You may have meant to use the base dir '.'"
  exit 1
)

# ------------------------------------------------------------

log 'Running environment customizations'

poetry_repos=('python-owsclient' 'python-pdp-sdk' 'python-ows-assets-uploader' 'python-owscontext' 'python-soundrecording-utils' 'python-aws-testing-utils' 'python-skill-eval-runner' 'python-test-fixtures')

if [[ "${GITREPO}" = 'python-orchard-features' ]]; then
  # https://github.com/splitio/python-client/issues/219
  # CFLAGS must be set before sync so the splitio cpphash extension compiles.
  export CFLAGS='-std=c99'
  uv sync --frozen
elif [[ "${GITREPO}" == 'python-owsrequest' ]]; then
  make pip_dev
elif [[ " ${poetry_repos[@]} " =~ " ${GITREPO} " ]]; then
  poetry install
elif [[ "${GITREPO}" == 'python-fansifter-common' ]]; then
  python -m pip install -e '.[dev]'
elif [[ "${GITREPO}" == 'python-jwtauth' ]]; then
  poetry install --all-extras
elif [[ -f uv.lock ]]; then
  uv sync --frozen
elif [[ -f requirements-dev.txt ]]; then
  python -m pip install -q -r requirements-dev.txt
fi

# ------------------------------------------------------------

log 'Bumping package version'

bumpversion "${VERSION}"

# ------------------------------------------------------------

log 'Pushing new version to Github'

git push origin "${TARGET_BRANCH}"
git push origin --tags

# ------------------------------------------------------------

# Add `python-jwtauth` to the poetry repos list
# so it uses the proper packaging and upload commands below.
poetry_repos+=('python-jwtauth')

log 'Uploading package to Pypi server'

if [[ "${GITREPO}" == 'python-abacus-common-data' ]]; then
  python setup.py sdist bdist_wheel
elif [[ " ${poetry_repos[@]} " =~ " ${GITREPO} " ]]; then
  poetry build
elif [[ -f uv.lock ]]; then
  uv build
else
  python setup.py sdist bdist_wheel
fi

if [[ -f uv.lock ]]; then
  # shellcheck source=/dev/null
  source /app/.uvpypiorch
  uv publish
else
  twine upload -r pypi-orch dist/*
fi
