#!/bin/bash

. "${MFEXT_HOME}/lib/bash_utils.sh"

set -eu

function usage() {
    echo "usage: download_compile_requirements /path/to/requirements.txt"
}

if test "${1:-}" = "--help"; then
    usage
    exit 0
fi
if test "${1:-}" = ""; then
    usage
    exit 1
fi
REQUIREMENTS="$1"
REALPATH=$(readlink -m "${REQUIREMENTS}")
REALDIRNAME=$(dirname "${REALPATH}")
OVERRIDE=0
if test -f "${REALDIRNAME}/override"; then
    OVERRIDE=1
fi
if test -f "${REALDIRNAME}/allow_binary_packages"; then
    if test ! -s "${REALDIRNAME}/allow_binary_packages"; then
        BINARY=""
    else
        BLIST=$(cat "${REALDIRNAME}/allow_binary_packages" | xargs | sed -e 's/ /,/g')
        BINARY="--no-binary :all: --only-binary ${BLIST}"
    fi
else
    BINARY="--no-binary :all:"
fi

     
TEMPO_LAYER_LABEL="tempolayer$$"
TEMPO_LAYER_PATH="$(pwd)/${TEMPO_LAYER_LABEL}"

CONSTRAINT=""
IFS=":" read -ra PATHS <<< "${PYTHONPATH:-}"
if test "${PATHS:-}" != ""; then
    for P in "${PATHS[@]}"; do
        F="${P}/requirements${METWORK_PYTHON_MODE:-}.txt"
        if test -f "${F}"; then
            CONSTRAINT="${CONSTRAINT} -c ${F}"
        fi
    done
fi

bootstrap_layer.sh "${TEMPO_LAYER_LABEL}" "${TEMPO_LAYER_PATH}"
layer_load "${TEMPO_LAYER_PATH}" >&2

mkdir -p "${TEMPO_LAYER_PATH}/tmp"
export TMPDIR="${TEMPO_LAYER_PATH}/tmp"
mkdir -p src
mkdir -p tmp_src

N=$(cat "${REQUIREMENTS}" |grep -c "^[^#].*[a-zA-Z0-9].*" || true)
if test "${N}" -eq 0; then
    rm -Rf "${TEMPO_LAYER_PATH}"
    rm -Rf tmp_src
    exit 0
fi

if test "${METWORK_PYTHON_MODE:-}" = "3"; then
    # If file build_isolate is not present (this is the default) pip wheel is run with option --no-build-isolation
    #  ==> all dependencies must be installed before pip wheel is run (including build dependencies in PEP517 pyproject.toml)
    # If file build_isolate is present, pip wheel is not run with option --no-build-isolation
    #  ==> Build dependencies from pyproject.toml files (such as flit, poetry, numpy or Cython)
    #      are installed during wheels building, regardless wheels already built
    #  ==> It's practical but it can lead to complex binary incompatibilities (for example with Cython) 
    if test -f "${REALDIRNAME}/build_isolate"; then
        BUILD_ISOLATION=""
    else
        BUILD_ISOLATION="--no-build-isolation"
    fi
else
    BUILD_ISOLATION=""
fi

if test ${OVERRIDE} = 1; then
    CONSTRAINT=""
fi

# shellcheck disable=SC2086
unsafe_pip wheel ${BUILD_ISOLATION} --wheel-dir=./src --src=./tmp_src ${BINARY} -r "${REQUIREMENTS}" ${CONSTRAINT} >&2
rm -Rf tmp_src

rm -Rf "${TEMPO_LAYER_PATH}"
