#!/bin/sh

# SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0

# Description:
#   This script will determine the Python version and work as a wrapper for it
#   It will choose in order: python, python3, python2

my_path=$(cd "$(dirname "$0")"; pwd)

if [ -f "$1" ]; then
    glidein_config="$1"
    # TODO: find a better way to recognize that is invoked in configuration w/ glidein_config as parameter (e.g header)
    # retained the use of grep since these are the only occurrences where variables values are being fetched and both these variables are immutable by scripts
    error_gen=$(grep '^ERROR_GEN_PATH ' "$glidein_config" | awk '{print $2}')
    work_dir=$(grep '^GLIDEIN_WORK_DIR ' "$glidein_config" | awk '{print $2}')
fi

[ -n "$error_gen" ] && CONFIG=TRUE  # invoked during the startup/setup

if command -v python > /dev/null 2>&1; then
    PYTHON="python"
elif command -v python3 > /dev/null 2>&1; then
    PYTHON="python3"
elif command -v python2 > /dev/null 2>&1; then
    PYTHON="python2"
fi

if [ -z "$PYTHON" ]; then
    echo "$0: python not found" >&2
    if [ -n "$CONFIG" ]; then
        "$error_gen" -ok "libtest.sh" "WN_Resource" "Python not found."
    fi
    exit 1
fi

if [ -n "$GLIDEIN_DEBUG" ]; then
    echo "$0: python executable: $(command -v $PYTHON)" >&2
    echo "$0: python version: $($PYTHON --version)" >&2
fi

if [ -n "$CONFIG" ]; then
    # during startup create the directories and exit successfully
    mkdir -p "$work_dir"/lib/python "$work_dir"/lib/python2 "$work_dir"/lib/python3
    "$error_gen" -ok "libtest.sh" "WN_Resource" "$($PYTHON --version)"
else
    # invoked to execute a python script
    # Apply the path correction if it ends in /bin:
    # it may have been moved to the glidein bin dir (gwms/bin) with the libraries moved to the lib dir (gwms/lib)
    export PYTHONPATH="$PYTHONPATH:${my_path%/bin}/lib/python"
    [ "$PYTHON" != python ] && export PYTHONPATH="$PYTHONPATH:${my_path%/bin}/lib/$PYTHON"
    exec $PYTHON "$@"
    echo "$0: failed to execute $PYTHON" >&2
    exit 1
fi
