#!/bin/bash

# Hab needs to modify the existing terminal's environment in some cases.
# To do this we can't use a setuptools exe and must use a script the terminal
# supports. This calls the python module cli passing the arguments to it and
# ends up calling the script file that code generates if required.

# Generate a unique temp directory to contain all of our script files
temp_directory=$(mktemp -d 2>/dev/null || mktemp -d -t 'hab')
temp_launch_file=$temp_directory/hab_launch.sh
temp_config_file=$temp_directory/hab_config.sh

# Ensure the tempfiles are remove on exit if they were created
trap "rm -rf $temp_directory" EXIT

# Calculate the command to run python with
if [[ ! -z "${HAB_PYTHON}" ]]; then
    # If HAB_PYTHON is specified, use it explicitly
    py_exe="${HAB_PYTHON}"
elif [[ -z "${VIRTUAL_ENV}" ]]; then
    # Otherwise if we are not in a virtualenv use system defined generic
    # python call for the given os if not inside a virtualenv
    unameOut="$(uname -s)"
    case "${unameOut}" in
        Linux*)     py_exe=python3;;
        Darwin*)    py_exe=python3;;
        # Assume other os's are windows
        *)          py_exe="py -3"
    esac
else
    # We are inside a virtualenv, so just use the python command
    py_exe="python"
fi

# Call our worker python process that may write the temp filename
$py_exe -m hab --script-dir $temp_directory --script-ext ".sh" "$@"

# Run the launch or config script if it was created on disk
if test -f "$temp_launch_file"; then
    . $temp_launch_file
elif test -f "$temp_config_file"; then
    . $temp_config_file
fi
