#!/usr/bin/env bash
set -eux -o pipefail

# This script is used to generate requirements.txt and requirements-dev.txt from the contents of setup.cfg

# cd to the directory one higher than this script
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1

# Exit if setup.cfg is not present
if [[ ! -f setup.cfg ]]; then
  echo "setup.cfg not found"
  exit 1
fi

# If --force then delete requirements.txt and requirements-dev.txt
if [[ "${1-''}" == "--force" ]]; then
  rm -f .requirements.sha256 requirements.txt requirements-dev.txt
fi

# This function is used to extract the requirements from setup.cfg
all_requirements=$(python3 <<END
import configparser

config = configparser.ConfigParser()
config.read('setup.cfg')
reqs = ''
if 'install_requires' in config['options']:
    reqs += config['options']['install_requires']
if 'options.extras_require' in config:
    for _, extra_reqs in config['options.extras_require'].items():
        reqs += extra_reqs
print(reqs)
END
)

checksum_file=".requirements.sha256"
checksum=$(echo "${all_requirements}" | sha256sum)

if [[ -f ${checksum_file} ]]; then
	old_checksum="$(tail -n 1 "${checksum_file}")"
else
  old_checksum=""
fi

if [[ ${checksum} == "${old_checksum}" ]]; then
  echo "No updated requirements"
  exit 0
else
  if [[ "${1-''}" == "--check-unchanged" ]]; then
    exit 8
  fi
fi


export CUSTOM_COMPILE_COMMAND="scripts/gen_requirements.sh"

# pip-compile requirements.txt
pip-compile \
  --resolver=backtracking \
  --allow-unsafe \
  --strip-extras \
  --extra-index-url https://us-python.pkg.dev/ce-builder/python/simple/ \
  --output-file requirements.txt \
  setup.cfg

# pip-compile requirements-dev.txt
pip-compile \
  --resolver=backtracking \
  --allow-unsafe \
  --strip-extras \
  --extra dev \
  --extra-index-url https://us-python.pkg.dev/ce-builder/python/simple/ \
  --pip-args=--constraint=requirements.txt \
  --output-file requirements-dev.txt \
  setup.cfg

echo "# File autogenerated by scripts/gen_requirements.sh, do not touch!"$'\n' > "${checksum_file}"
echo "${checksum}" >> "${checksum_file}"
