#!/usr/bin/env bash

set -e

if [ "${SW_TASK_DISABLE_DEBUG}" != "1" ]; then
    set -x
fi

ulimit -n 65535 || true

CONDA_BIN="/opt/miniconda3/bin"
SWMP_DIR=${SW_SWMP_WORKDIR:=/opt/starwhale/swmp}
SWRT_DIR=${SW_SWRT_WORKDIR:=/opt/starwhale/swrt}
PIP_CACHE_DIR=${SW_PIP_CACHE_DIR:=/root/.cache/pip}
VERBOSE="-vvvv"
STEP=${SW_TASK_STEP:-""}
TASK_INDEX=${SW_TASK_INDEX:-0}
TASK_NUM=${SW_TASK_NUM:-0}

_update_python_alter() {
    echo "--> set python/python3 to $1 ..."
    update-alternatives --install /usr/bin/python3 python3 /usr/bin/$1 10
    update-alternatives --install /usr/bin/python python /usr/bin/$1 10
    python3 --version
}

pre_config() {
    echo "--> debug config ..."
    if [ "${SW_TASK_DISABLE_DEBUG}" = "1" ]; then
        VERBOSE="-v"
    fi

    echo "--> config pypi and conda config ..."

    if [ ${SW_PYPI_INDEX_URL} ] ; then
        echo -e "\t ** use SW_PYPI_* env to config ~/.pip/pip.conf"
        mkdir -p ~/.pip
        cat > ~/.pip/pip.conf << EOF
[global]
index-url = ${SW_PYPI_INDEX_URL}
extra-index-url = ${SW_PYPI_EXTRA_INDEX_URL}

[install]
trusted-host= ${SW_PYPI_TRUSTED_HOST}
EOF
        echo -e "\t ** current pip conf:"
        echo "-------------------"
        cat ~/.pip/pip.conf
        echo "-------------------"
    else
        echo -e "\t ** use image builtin pip.conf"
    fi
}

set_pip_cache() {
    echo "\t ** set pip cache dir:"
    python3 -m pip config set global.cache-dir ${PIP_CACHE_DIR} || true
    python3 -m pip cache dir || true
}

pre_check() {
    echo "--> run pre check for swmp model dir ..."
    if [ ! -f "${SWMP_DIR}/model.yaml" ] || [ ! -d "${SWMP_DIR}/src" ]; then
        echo "${SWMP_DIR} is not starwhale swmp target dir, will exit"
        exit 1
    fi

    echo "--> run pre check for swrt runtime dir ..."
    if [ ! -f "${SWRT_DIR}/_manifest.yaml" ] || [ ! -d "${SWRT_DIR}/dependencies" ]; then
        echo "${SWRT_DIR} is not starwhale swrt target dir, will exit"
        exit 1
    fi

    if [ "${SWRT_DIR}" = "${SWMP_DIR}" ]; then
        echo "swmp and swrt use the same dir, will exit"
        exit 1
    fi
}

set_python() {
	# yq only installed for py3.8
    _MANIFEST_RUNTIME=$(python3.8 -m yq -r .environment.python ${SWRT_DIR}/_manifest.yaml) || exit 1
    _RUNTIME="python${_MANIFEST_RUNTIME}"

    echo "**** DETECT RUNTIME: ${_RUNTIME}"

    if [ "$_RUNTIME" = "python3.7" ] || [ "$_RUNTIME" = "python3.9" ] || [ "$_RUNTIME" = "python3.10" ] ; then
        _update_python_alter "$_RUNTIME"
    else
        _update_python_alter "python3.8"
    fi
}

# TODO:restore when processing evaluation(eval run use param: 'runtime URI', and it can be uri or dir path )
restore_activate_runtime() {
    echo '--> restore python env ...'
    export PYTHONWARNINGS="ignore:Unverified HTTPS request"
    swcli ${VERBOSE} runtime restore ${SWRT_DIR} || exit 1
    unset PYTHONWARNINGS

    echo '--> source activate ...'
    eval "$(${SWRT_DIR}/activate.sw)" || exit 1
}

run() {
    echo "--> start to run swmp ${STEP}, use $(which swcli) cli @ ${SWMP_DIR} ..."
    swcli ${VERBOSE} model eval "${SWMP_DIR}"/src --step=${STEP} --task-index=${TASK_INDEX} --override-task-num=${TASK_NUM} --version=${SW_EVALUATION_VERSION} || exit 1
}

welcome() {
    echo "===================================="
    echo "StarWhale Docker Entrypoint"
    echo "Date: `date -u +%Y-%m-%dT%H:%M:%SZ`"
    echo "Version: `swcli --version`"
    echo "Run: $1 "
    echo "Model Version: ${SW_SWMP_NAME}@${SW_SWMP_VERSION}"
    echo "Model Workdir: ${SWMP_DIR}"
    echo "Runtime Workdir: ${SWRT_DIR}"
    echo "===================================="
}

eval_task_prepare(){
    welcome $1
    pre_config
    pre_check
    set_python
    set_pip_cache
    restore_activate_runtime
}

case "$1" in
    pre_config)
        pre_config
        ;;
    run)
        eval_task_prepare $1 && run
        ;;
    *)
        exec "$@"
        ;;
esac
