#!/usr/bin/env bash

set -eu

repo_dir="$(readlink -f "$(dirname "${BASH_SOURCE[0]}")/..")"

if [ -n "${CC_ROOT_DIR:-}" ]; then
  running_in_pipeline=true
else
  running_in_pipeline=false
fi

if ${running_in_pipeline}; then
  version="$(cat managed-version/version)"
  if echo "${version}"| grep -e-dev; then
    # workaround: pypi only allows numbers (not hex-strs); as we do not publish
    # snapshot-packages anyhow, it is okay to hardcode prerelease-suffix
    version="$(echo "${version}" | cut -d- -f1)-dev0"
  fi
  echo "${version}" | "${repo_dir}/.ci/write-version"
fi

if [ -n "${PYPI_PATH:-}" ]; then
  out_dir="$(readlink -f "${repo_dir}/../${PYPI_PATH:-}/dist")"
  mkdir "${out_dir}"
else
  out_dir="${repo_dir}"
fi

if [ ! -z "${VERSION_PATH:-}" ]; then
  effective_version="$(cat "${VERSION_PATH}/version")"
  last_release_tag_path="${repo_dir}/concourse/resources/LAST_RELEASED_TAG"
  if [ ! -f "${last_release_tag_path}" ]; then
    echo "ERROR: no such file ${last_release_tag_path}"
    exit 1
  fi
  echo "effective-version: ${effective_version}"
  echo "${effective_version}" > "${last_release_tag_path}"
else
  echo "WARNING: local build - LAST_RELEASED_TAG will not be patched"
fi

cd $repo_dir

if $running_in_pipeline; then
  # install build-only dependencies (no need to include in image)
  pip3 install --upgrade pip wheel setuptools
  pip3 uninstall -y gardener-cicd-cli gardener-cicd-libs
fi

# build into "${repo_dir}/dist"
python3 "${repo_dir}/setup.oci.py" sdist bdist_wheel
python3 "${repo_dir}/setup.py" sdist bdist_wheel
python3 "${repo_dir}/setup.whd.py" sdist bdist_wheel

# keep for subsequent docker build
cp dist/* ${out_dir}


###############################
# gardener-cicd-cli

cli_dir="${repo_dir}/cli"
cd "${cli_dir}"
python3 "${cli_dir}/setup.py" sdist bdist_wheel

# do not cp for local build
if [ "${out_dir}" != "${repo_dir}" ]; then
  # keep for subsequent docker build + publish-to-pypi
  cp dist/* ${out_dir}
  echo "built packages:"
  ls -lta "${out_dir}"
fi
