#!/usr/bin/env bash

unset PYENV_VERSION

if [[ ! -d $PYENV_ROOT ]]
then
    export PYENV_ROOT="$HOME/.pyenv"
fi

declare -r PROJDIR="$PWD"
if [[ ! -s $PROJDIR/riak/__init__.py ]]
then
    echo "[ERROR] script must be run from the clone of github.com/basho/riak-python-client" 1>&2
    exit 1
fi

rm -f $PROJDIR/.python-version

# Install pyenv if it's missing
if [[ ! -d $PYENV_ROOT ]]
then
    git clone 'https://github.com/yyuu/pyenv.git' $PYENV_ROOT
else
    (cd $PYENV_ROOT && git fetch --all)
fi

(cd $PYENV_ROOT && git checkout $(git describe --tags $(git rev-list --tags --max-count=1)))

declare -r pyenv_alias_dir="$PYENV_ROOT/plugins/pyenv-alias"
if [[ ! -d $pyenv_alias_dir ]]
then
    git clone 'https://github.com/s1341/pyenv-alias.git' $pyenv_alias_dir
else
    (cd $pyenv_alias_dir && git pull origin master)
fi

# Add pyenv root to PATH
# and initialize pyenv
if [[ $PATH != */.pyenv* ]]
then
    echo "[INFO] adding $PYENV_ROOT/bin to PATH"
    export PATH="$PYENV_ROOT/bin:$PATH"
fi

if [[ $(type -t pyenv) != 'function' ]]
then
    echo "[INFO] init pyenv"
    eval "$(pyenv init -)"
fi

do_pip_upgrades='false'

# NB: 2.7.8 is special-cased
for pyver in 2.7 3.3 3.4 3.5
do
    riak_py_alias="riak_$pyver"
    if ! pyenv versions | fgrep -v 'riak_2.7.8' | fgrep -q "$riak_py_alias"
    then
        # Need to install it
        do_pip_upgrades='true'

        declare -i pymaj="${pyver%.*}"
        declare -i pymin="${pyver#*.}"
        pyver_latest="$(pyenv install --list | grep -E "^[[:space:]]+$pymaj\\.$pymin\\.[[:digit:]]+\$" | tail -n1 | sed -e 's/[[:space:]]//g')"

        echo "[INFO] installing Python $pyver_latest"
        VERSION_ALIAS="$riak_py_alias" pyenv install "$pyver_latest"
    fi
done

if ! pyenv versions | fgrep -q 'riak_2.7.8'
then
    # Need to install it
    do_pip_upgrades='true'

    echo "[INFO] installing Python 2.7.8"
    VERSION_ALIAS='riak_2.7.8' pyenv install '2.7.8'
fi

pushd $PROJDIR
pyenv local 'riak_3.5' 'riak_3.4' 'riak_3.3' 'riak_2.7' 'riak_2.7.8'

pyenv rehash

if [[ $do_pip_upgrades == 'true' ]]
then
    for PY in $(pyenv versions --bare --skip-aliases | grep '^riak_')
    do
        echo "[INFO] $PY - upgrading pip / setuptools"
        PYENV_VERSION="$PY" pip install --upgrade pip setuptools
    done
fi

python_version="$(python --version)"
if [[ $python_version == Python\ 3* ]]
then
    pip install --ignore-installed tox
    if ! pip show --quiet tox
    then
        echo "[ERROR] install of 'tox' failed" 1>&2
        popd
        exit 1
    fi
    pyenv rehash
else
    echo "[ERROR] expected Python 3 to be 'python' at this point" 1>&2
    popd
    exit 1
fi

popd
