#!/bin/bash -ex

_build()
{
    cd $1

    # setup virtual env
    pyvenv env
    source env/bin/activate

    # update to latest pip, setuptools
    pip install -U pip
    pip install -U setuptools

    # ensure latest flake8 before we start
    pip install -U flake8

    # ensure PEP8 compliant
    flake8 .

    # setup package dependencies
    platform=`uname`
    if [ $platform = 'Darwin' ] && [ -f osx_build.opts ]; then
        source osx_build.opts && pip install -e .
    else
        pip install -e .
    fi

    # setup any test dependencies that setuptools/easy_install can't handle
    if [ -f reqs-test.pip ]; then
        pip install -r reqs-test.pip
    fi

    # install test dependencies and run unittests via test target
    python setup.py test

    # cleanup
    deactivate
    rm -Rf env
    find . -name __pycache__ | xargs rm -Rf
    cd ..
}

# either build dir arg or walk through all contrib-* dirs and build
if [ $1 ]; then
    _build $1
else
    for dir in contrib-*; do
        _build $dir
    done
fi
