#!/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
#Until pip 23, wheel cache was not used with option --no-binary
#With pip 23, wheel cache will be used with option --no-binary (it will speed up Metwork build)
#Option --use-feature=no-binary-enable-wheel-cache reproduce this behavior with pip 22
#Option --use-feature=no-binary-enable-wheel-cache is now always enabled
BLIST1=$(cat "${MFEXT_HOME}/share/build_dependencies" | xargs | sed -e 's/ /,/g')
if test -f "${REALDIRNAME}/allow_binary_packages"; then
    if test ! -s "${REALDIRNAME}/allow_binary_packages"; then
        BINARY=""
    else
        BLIST2=$(cat "${REALDIRNAME}/allow_binary_packages" | xargs | sed -e 's/ /,/g')
        BLIST=${BLIST1},${BLIST2}
        BINARY="--no-binary :all: --only-binary ${BLIST}"
    fi
else
    BINARY="--no-binary :all: --only-binary ${BLIST1}"
fi

BUILD_CONSTRAINT=""
if test -f "${REALDIRNAME}/build_constraint"; then
    BUILD_CONSTRAINT="--build-constraint ${REALDIRNAME}/build_constraint"
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 ${OVERRIDE} = 1; then
    CONSTRAINT=""
fi

# shellcheck disable=SC2086
unsafe_pip wheel --wheel-dir=./src --src=./tmp_src ${BINARY} -r "${REQUIREMENTS}" ${BUILD_CONSTRAINT} ${CONSTRAINT} | grep --color=always -E 'Downloading|$' >&2
rm -Rf tmp_src

rm -Rf "${TEMPO_LAYER_PATH}"
