#! /usr/bin/env bash
set -e

[[ "$TOXENV" == *-flake8 || "$TOXENV" == pypy* ]] && exit 0

umask 022 &&
chmod -R a+rX . &&

py=$(python -c "import sys; print('.'.join(sys.version.split('.')[:2]))")
v=$(echo "$py" | sed 's/\.//') &&

pip install -U "pip<19.2" "setuptools<44" "readme-renderer<25.0" "twine<2.0" &&
if [ "$py" == 3.4 ]; then
    pip install -U "wheel==0.31.1"
else
    pip install -U "wheel==0.34.1"
fi &&
python setup.py sdist &&

if [ -d build ]; then find build -name '*.py[co]' -delete; fi &&
python setup.py build_ext &&
python setup.py build --executable '/usr/bin/env python' &&
python    -m compileall build &&
python -O -m compileall build &&
python setup.py bdist_wheel &&

if [ "$TRAVIS_OS_NAME" == 'linux' ]; then
    if [ "$py" == 2.7 ]; then
        pyenv global system 3.6.7 2.7.15
        pip3.6 install -U "auditwheel==3.1.0"
    elif [ "$py" == 3.4 ]; then
        pip install -U typing "auditwheel==2.1.1"
    else
        pip install -U "auditwheel==3.1.0"
    fi &&

    for f in dist/Cheetah3-*-cp$v-*-linux_x86_64.whl; do
        if [ "$py" == 2.7 ]; then
            python3.6 -m auditwheel repair -w dist/ "$f"
        else
            python -m auditwheel repair -w dist/ "$f"
        fi &&
        rm -f "$f"
    done

elif [ "$TRAVIS_OS_NAME" == 'osx' ]; then
    pip install -U delocate
    for f in dist/Cheetah3-*-cp$v-*-macosx*.whl; do
        delocate-wheel -v "$f"
    done
fi &&

# TWINE_USERNAME / TWINE_PASSWORD / TWINE_REPOSITORY_URL
# must be set in Travis settings.
exec twine upload --skip-existing dist/*
