#!/bin/sh

if [ -n "${PULUMI_RUNTIME_VIRTUALENV:-}" ] ; then
    # Remove trailing slash.
    PULUMI_RUNTIME_VIRTUALENV=${PULUMI_RUNTIME_VIRTUALENV%/}

    # Make the path absolute (if not already).
    case $PULUMI_RUNTIME_VIRTUALENV in
        /*) : ;;
        *) PULUMI_RUNTIME_VIRTUALENV=$PWD/$PULUMI_RUNTIME_VIRTUALENV;;
    esac

    # If python exists in the virtual environment, set PATH and run it.
    if [ -f "$PULUMI_RUNTIME_VIRTUALENV/bin/python" ]; then
        # Update PATH and unset PYTHONHOME.
        PATH="$PULUMI_RUNTIME_VIRTUALENV/bin:$PATH"
        export PATH
        if [ -n "${PYTHONHOME:-}" ] ; then
            unset PYTHONHOME
        fi

        # Run python from the virtual environment.
        "$PULUMI_RUNTIME_VIRTUALENV/bin/python" -u -m pulumi.dynamic $@
    else
        if [ -d "$PULUMI_RUNTIME_VIRTUALENV" ]; then
            1>&2 echo "The 'virtualenv' option in Pulumi.yaml is set to \"$PULUMI_RUNTIME_VIRTUALENV\", but \"$PULUMI_RUNTIME_VIRTUALENV\" doesn't appear to be a virtual environment."
        else
            1>&2 echo "The 'virtualenv' option in Pulumi.yaml is set to \"$PULUMI_RUNTIME_VIRTUALENV\", but \"$PULUMI_RUNTIME_VIRTUALENV\" doesn't exist."
        fi
        1>&2 echo "Run the following commands to create the virtual environment and install dependencies into it:"
        1>&2 echo "    1. python3 -m venv $PULUMI_RUNTIME_VIRTUALENV"
        1>&2 echo "    2. $PULUMI_RUNTIME_VIRTUALENV/bin/python -m pip install --upgrade pip setuptools wheel"
        1>&2 echo "    3. $PULUMI_RUNTIME_VIRTUALENV/bin/python -m pip install -r $PWD/requirements.txt"
        1>&2 echo "For more information see: https://www.pulumi.com/docs/intro/languages/python/#virtual-environments"
        exit 1
    fi
else
    # Otherwise, run either PULUMI_PYTHON_CMD (if set) or python3.
    "${PULUMI_PYTHON_CMD:-python3}" -u -m pulumi.dynamic $@
fi