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

echo "---> Python Buildpack"

# 1. GET ARGS
layers_dir=$1
plan_path=$3

# shellcheck source=/dev/null
. generate-project.sh "${layers_dir}"

# 2. Install build deps
# shellcheck source=/dev/null
. generate-layers.sh "${layers_dir}"
generate_deps_layer build-deps
generate_deps_layer run-deps

# 3. install python
generate_stack_layer python "${plan_path}" true
# shellcheck source=/dev/null
. init-stack

python_layer_dir="${layers_dir}"/python
rm -f "${python_layer_dir}/profile.d/pip.sh"
if [ "${PIP_INDEX_URL}" ]; then
  tee >>"${python_layer_dir}/profile.d/pip.sh" <<EOF
python -m pip  config set global.index-url "${PIP_INDEX_URL}"
EOF
fi
if [ "${PIP_EXTRA_INDEX_URL}" ]; then
  tee >>"${python_layer_dir}/profile.d/pip.sh" <<EOF
python -m pip  config set global.extra-index-url "${PIP_INDEX_URL}"
EOF
fi

# Compares previous requirements checksum to the current requirements
requirements_layer_dir="${layers_dir}/requirements"
local_requirements_checksum=$(sha256sum requirements.txt | cut -d ' ' -f 1 || echo 'not found')
remote_requirements_checksum='not found'
if [[ -f "${requirements_layer_dir}.toml" ]]; then
  remote_requirements_checksum=$(yj <"${requirements_layer_dir}.toml" -t | jq -r .metadata.version 2>/dev/null || echo 'not found')
fi
mkdir -p "${requirements_layer_dir}"

if [ "${PIP_INDEX_URL}" ]; then
  echo "---> Setting pip index-url with ${PIP_INDEX_URL}"
  python -m pip config set global.index-url "${PIP_INDEX_URL}"
fi
if [ "${PIP_EXTRA_INDEX_URL}" ]; then
  echo "---> Setting pip extra-index-url with ${PIP_EXTRA_INDEX_URL}"
  python -m pip config set global.extra-index-url "${PIP_EXTRA_INDEX_URL}"
fi

cat >"${requirements_layer_dir}.toml" <<EOL
[types]
cache = true
build = true
launch = true

[metadata]
version = "${local_requirements_checksum}"
EOL
if [[ -f requirements.txt && "${local_requirements_checksum}" == "${remote_requirements_checksum}" ]]; then
  echo "---> Reusing requirements"
elif [[ -f requirements.txt ]]; then
  echo "---> Installing requirements with pip"
  python -m pip install -r requirements.txt \
    --exists-action=w --src="${python_layer_dir}"/src \
    --disable-pip-version-check --no-cache-dir
  scanelp "${python_layer_dir}" > "${BASE_LAYER}"/deps/.auto-deps
  generate_deps_layer auto-deps
fi

generate-launch.sh "${layers_dir}"
