#!/bin/bash
#
# Copyright 2018-2018 Ghent University
#
# This file is part of vsc-install,
# 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),
# the 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/hpcugent/vsc-install
#
# vsc-install is free software: you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as
# published by the Free Software Foundation, either version 2 of
# the License, or (at your option) any later version.
#
# vsc-install 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 Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with vsc-install. If not, see <http://www.gnu.org/licenses/>.
#
### END OF HEADER

# -e  Exit immediately if a command exits with a non-zero status.
# -u  Treat unset variables as an error when substituting.
set -e -u

# actual python binary that we'll call
PYTHON=/usr/bin/python

# avoid weird issue with grep (for example, colored output)
unset GREP_OPTIONS

# only actually print debug info if $PYTHON_STRIPPED_ENV_DEBUG is defined
function debug {
    if [ -n "${PYTHON_STRIPPED_ENV_DEBUG:-}" ]; then
        echo "[python-stripped-env] $1"
    fi
}

debug "which python: $(command -v python)"

# unset all $LD_* environment variables
for env_var in $(env | grep -E '^LD_' | cut -f1 -d'='); do
    debug "Unsetting \$$env_var (value was: ${!env_var})"
    unset $env_var
done

debug "All \$PYTHON* environment variables that matter are ignored by using 'python -E'"
debug "Found defined \$PYTHON* environment variables:"
for env_var in $(env | grep '^PYTHON' | cut -f1 -d'=' | grep -v PYTHON_STRIPPED_ENV_DEBUG); do
    debug "> \$$env_var was: ${!env_var}"
done

# -s: ignore $HOME/.local/python*/site-packages
# see https://docs.python.org/2/using/cmdline.html#cmdoption-s
# and https://docs.python.org/2/library/site.html#site.USER_SITE
# -E: ignore $PYTHONPATH and $PYTHONHOME
# see https://docs.python.org/2/using/cmdline.html#cmdoption-e
debug "$PYTHON -s -E $(echo "$@")"
$PYTHON -s -E "$@"
