#!/usr/bin/env bash

set -o pipefail

if [ "${TRAVIS_OS_NAME}" == "linux" ] ; then
    PYTHON_VERSIONS="${TRAVIS_PYTHON_VERSION}"
else
    PYTHON_VERSIONS="$(find -E `echo $PATH | tr : ' '` -depth 1 -regex '.*/python(3.[0-9]+)|.*/pypy|.*/pypy3' 2>/dev/null | sed -E -e 's/.*python//' -e 's/.*pypy/pypy/' )"
fi
# This fancy line makes it so we test each module individually, and then all of green.
#TESTS="`find green -name test_*.py | sed -e s/.py$// | tr / .` green"
TESTS="green"


if [ "${TESTS}" == "" ] ; then
    echo "No tests found!"
    exit 2
fi

if [ "${PYTHON_VERSIONS}" == "" ] ; then
    PYTHON_VERSIONS="default"
fi

if [[ "${PYTHON_VERSIONS}" == *-dev ]] ; then
    PYTHON_VERSIONS="${PYTHON_VERSIONS::-4}"
fi

# Deduplicate
PYTHON_VERSIONS="$(echo $PYTHON_VERSIONS | xargs -n1 | sort -u | xargs)"


echo "Identified python versions: `echo ${PYTHON_VERSIONS} | tr '\n' ' '`"

# Make sure each of the pythons has the necessary requirements installed
for PYTHON_VERSION in ${PYTHON_VERSIONS} ; do
    if [ "${PYTHON_VERSION}" == "default" ] ; then
        PYTHON_VERSION="3"
    fi
    if [ "${PYTHON_VERSION}" == "nightly" ] ; then
        PYTHON_VERSION=""
    fi
    if [[ -e `which python${PYTHON_VERSION}` ]] ; then
        PYTHON=python${PYTHON_VERSION}
        shift
    elif [[ -e `which ${PYTHON_VERSION}` ]] ; then
        PYTHON=${PYTHON_VERSION}
        shift
    elif [[ ${PYTHON_VERSION} =~ ^pypy2.*$ ]] ; then
        PYTHON=pypy
        shift
    elif [[ ${PYTHON_VERSION} =~ ^pypy3.*$ ]] ; then
        PYTHON=pypy3
        shift
    else
        echo "Failed to determine python binary for python version '${PYTHON_VERSION}'"
        exit 4
    fi

    if ! ${PYTHON} -m pip > /dev/null ; then
        echo "Please install pip under ${PYTHON}"
        exit 5
    fi

    VENV_DIR="venv${PYTHON_VERSION}"
    if [ ! -d ${VENV_DIR} ] ; then
        ${PYTHON} -m venv ${VENV_DIR}
    fi

    echo "Ensuring dependencies are installed for ${VENV_DIR}"

    if ! source ${VENV_DIR}/bin/activate ; then
        echo "Failed to enter virtual environment"
        exit 7
    fi
    hash -r
    ${VENV_DIR}/bin/pip install -r requirements.txt | grep -Ev "Requirement already|however version|consider upgrading"
    ${VENV_DIR}/bin/pip install -r requirements-dev.txt | grep -Ev "Requirement already|however version|consider upgrading"
    deactivate
done

# Finally, run all the tests
for TEST in ${TESTS} ; do
    for PYTHON_VERSION in ${PYTHON_VERSIONS} ; do
        if [ "${PYTHON_VERSION}" == "default" ] ; then
            PYTHON="python3"
        else
            VENV_DIR="venv${PYTHON_VERSION}"
            PYTHON=${VENV_DIR}/bin/python
        fi

        echo ""
        set -x
        # Actually run it!
        if ! PYTHONPATH="." ${PYTHON} -m green.cmdline -k ${TEST} ; then
            exit 3
        fi
        { set +x; } 2>/dev/null
    done
done

echo -e "\nCompleted internal test suite for Python versions:\n${PYTHON_VERSIONS}\n"
