#!/bin/bash

function usage() {
    echo "usage: envtpl [ENVTPL_ARG1] [ENVTPL_ARG2] [...]"
    echo "  => envtpl wrapper, load python3 layer dynamically but also use"
    echo "     some other locations because we use envtpl during build"
    echo "     (before python3/envtpl formal installation)"
}

if test "${1:-}" = "--help"; then
    usage
    exit 0
fi

if test -x "${MFEXT_HOME:-}/opt/python3/bin/envtpl"; then
    if test -x "${MFEXT_HOME:-}/opt/python3_core/bin/python"; then
        N=$("${MFEXT_HOME}/opt/core/bin/is_layer_installed" python3@mfext 2>&1)
        if test "${N}" != "1"; then
            # probably during a module bootstrap
            export LAYERAPI2_LAYERS_PATH="${MFEXT_HOME}/opt:${MFEXT_HOME}"
            # FIXME: do not hardcode this
            export PYTHON3_SHORT_VERSION=3.13
        fi
        ENVTPL="${MFEXT_HOME:-}/opt/python3/bin/envtpl"
        exec "${MFEXT_HOME}/opt/core/bin/layer_wrapper" --layers=python3@mfext -- "${ENVTPL}" "$@"
        exit 1
    fi
fi

if test -x "${SRC_DIR:-}/bootstrap/bin/penvtpl"; then
    ENVTPL=${SRC_DIR:-}/bootstrap/bin/penvtpl
    # https://stackoverflow.com/questions/13941828/pyinstaller-executable-missing-module-struct-on-ubuntu-12-04-precise?rq=1
    unset LD_LIBRARY_PATH
    exec "${ENVTPL}" "$@"
    exit 1
fi

echo "ERROR: can't find a valid envtpl binary"
exit 1
