#!/bin/bash
##
# Copyright 2009-2022 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild.  If not, see <http://www.gnu.org/licenses/>.
##

# EasyBuild main script
# check Python version and run easybuild.main script

# @author: Stijn De Weirdt (Ghent University)
# @author: Dries Verdegem (Ghent University)
# @author: Kenneth Hoste (Ghent University)
# @author: Pieter De Baets (Ghent University)
# @author: Jens Timmerman (Ghent University)

keyboard_interrupt() {
    echo "Keyboard interrupt!"
    exit 1
}

trap keyboard_interrupt SIGINT

# Python 2.6+ or 3.5+ required
REQ_MIN_PY2VER=6
REQ_MIN_PY3VER=5

EASYBUILD_MAIN='easybuild.main'

# easybuild module to import to check whether EasyBuild framework is available;
# don't use easybuild.main here, since that's a very expensive module to import (it makes the 'eb' command slow)
EASYBUILD_IMPORT_TEST='easybuild.framework'

function verbose() {
    if [ -n "${EB_VERBOSE}" ]; then echo ">> $1"; fi
}

PYTHON=
# When selecting the PYTHON command to use, we need to first take environment variable settings into account
# - EB_PYTHON is a variable set by the user that takes precedence over everything else
# - EB_INSTALLPYTHON is set when EasyBuild is installed as a module (by EasyBuild). It is set to the PYTHON
#   used during that installation (for example, you could override PYTHON using EB_PYTHON at installation
#   time, this variable preserves that choice).
for python_cmd in "${EB_PYTHON}" "${EB_INSTALLPYTHON}" 'python' 'python3' 'python2'; do

    verbose "Considering '${python_cmd}'..."

    # check whether python* command being considered is available
    # (using 'command -v', since 'which' implies an extra dependency)
    if { command -v "${python_cmd}" && "${python_cmd}" -V; } &> /dev/null; then

        # make sure Python version being used is compatible
        pyver=$("${python_cmd}" -V 2>&1 | cut -f2 -d' ')
        pyver_maj=$(echo "${pyver}" | cut -f1 -d'.')
        pyver_min=$(echo "${pyver}" | cut -f2 -d'.')

        if [ "${pyver_maj}" -eq 2 ] && [ "${pyver_min}" -ge "${REQ_MIN_PY2VER}" ]; then
            verbose "'${python_cmd}' version: ${pyver}, which matches Python 2 version requirement (>= 2.${REQ_MIN_PY2VER})"
            PYTHON="${python_cmd}"
        elif [ "${pyver_maj}" -eq 3 ] && [ "${pyver_min}" -ge "${REQ_MIN_PY3VER}" ]; then
            verbose "'${python_cmd}' version: ${pyver}, which matches Python 3 version requirement (>= 3.${REQ_MIN_PY3VER})"
            PYTHON="${python_cmd}"
        fi

        if [ -n "${PYTHON}" ]; then
            # check whether EasyBuild framework is available for selected python command
            if "${PYTHON}" -c "import ${EASYBUILD_IMPORT_TEST}" 2> /dev/null; then
                verbose "'${python_cmd}' is able to import '${EASYBUILD_IMPORT_TEST}', so retaining it"
            else
                # if EasyBuild framework is not available, don't use this python command, keep searching...
                verbose "'${python_cmd}' is NOT able to import '${EASYBUILD_IMPORT_TEST}' so NOT retaining it"
                unset PYTHON
            fi
        fi

        # break out of for loop if we've found a working python command
        if [ -n "${PYTHON}" ]; then
            break
        fi
    else
        verbose "No working '${python_cmd}' found in \$PATH, skipping..."
    fi
done

if [ -z "${PYTHON}" ]; then
    echo -n "ERROR: No compatible 'python' command found via \$PATH " >&2
    echo "(EasyBuild requires Python 2.${REQ_MIN_PY2VER}+ or 3.${REQ_MIN_PY3VER}+)" >&2
    exit 1
else
    verbose "Selected Python command: ${python_cmd} ($(command -v "${python_cmd}"))"
fi

# enable optimization, unless $PYTHONOPTIMIZE is defined (use "export PYTHONOPTIMIZE=0" to disable optimization)
if [ -z "${PYTHONOPTIMIZE}" ]
then
    # instruct Python to turn on basic optimizations (equivalent to using 'python -O')
    export PYTHONOPTIMIZE=1
fi

if [ -z "${FANCYLOGGER_IGNORE_MPI4PY}" ]
then
    # avoid that fancylogger tries to import mpi4py to determine MPI rank
    export FANCYLOGGER_IGNORE_MPI4PY=1
fi

export EB_SCRIPT_PATH="${0}"

verbose "${PYTHON} -m ${EASYBUILD_MAIN} ${*}"
exec "${PYTHON}" -m "${EASYBUILD_MAIN}" "${@}"
