#!/usr/bin/env bash
set -euo pipefail

unames="$(uname -s)"
if [[ ${unames} =~ MINGW || ${unames} =~ CYGWIN || ${unames} =~ MSYS ]]; then
    is_windows=true
else
    is_windows=false
fi

if [ $# -eq 0 ] || [ $# -gt 2 ]; then
    echo "Usage: $0 <python> [venv-path]"
    echo "e.g."
    echo "$0 \$(which python3)"
    exit 1;
elif [ $# -eq 2 ]; then
    PYTHON="$1"
    VENV="$2"
elif [ $# -eq 1 ]; then
    PYTHON="$1"
    VENV="venv"
fi

if ! "${PYTHON}" -m venv --help > /dev/null 2>&1; then
    echo "Error: ${PYTHON} is not Python3?"
    exit 1
fi
if [ -e activate_python.sh ]; then
    echo "Warning: activate_python.sh already exists. It will be overwritten"
fi

"${PYTHON}" -m venv ${VENV}
if "${is_windows}"; then
    cat << EOF > activate_python.sh
#!/usr/bin/env bash
# THIS FILE IS GENERATED BY tools/setup_venv.sh
. $(cd ${VENV}; pwd)/Scripts/activate
EOF

else
    cat << EOF > activate_python.sh
#!/usr/bin/env bash
# THIS FILE IS GENERATED BY tools/setup_venv.sh
. $(cd ${VENV}; pwd)/bin/activate
EOF
fi

. ./activate_python.sh
python3 -m pip install -U pip wheel
