#!/bin/bash

if test -z "$WORKSPACE"; then
    echo "ERROR: \$WORKSPACE not defined"
    exit 1
fi
if test -n "$1"; then
    PYTHON="$1"
else
    PYTHON=python
fi
if test -n "$2"; then
    export CXX="$2"
else
    export CXX="g++"
fi

export BUILD_SCRIPTS="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export PATH="$WORKSPACE/vpython/bin:$PATH"

echo
echo "Building on `hostname`:"
echo
echo "  Workspace: ${WORKSPACE}"
echo "  Scripts: ${BUILD_SCRIPTS}"
echo
echo "  Environment:"
/usr/bin/env 2>&1 | sort | sed 's/^/    /'
echo
echo "  Python:"
"$PYTHON" -c 'import sys; sys.stdout.write(sys.version+"\n")' 2>&1 \
    | sed 's/^/    /'
PYTHON_VER=`"$PYTHON" -c 'import sys; sys.stdout.write(str(sys.version_info[0]))'`
echo
# The following executables are required (missing app yields build failure)
for app in $CXX; do
echo "  $app:"
$app --version 2>&1 | grep -v '^$' | sed 's/^/    /' || exit 1
echo
done


# Setup virtual Python environment
\rm -Rf "$WORKSPACE"/vpython
tmp=2.6
if [ "yes" = "$(echo | awk "($PYTHON_VER < $tmp) { print \"yes\"; }")" ]; then
   "$PYTHON" "$BUILD_SCRIPTS"/virtualenv_1.7.py "$WORKSPACE"/vpython || exit 1
else
   "$PYTHON" "$BUILD_SCRIPTS"/virtualenv.py "$WORKSPACE"/vpython || exit 1
fi
"$WORKSPACE"/vpython/bin/easy_install nose || exit 1
if test "$PYTHON_VER" -gt 2; then
    "$WORKSPACE"/vpython/bin/easy_install unittest2py3k || exit 1
else
    "$WORKSPACE"/vpython/bin/easy_install unittest2 || exit 1
fi
"$WORKSPACE"/vpython/bin/easy_install ply || exit 1
"$WORKSPACE"/vpython/bin/easy_install ordereddict || exit 1
"$WORKSPACE"/vpython/bin/easy_install pyutilib.th || exit 1

# Install our source
#  -- not necessary: nosetests will add the source to the sys.path.
#"$WORKSPACE"/vpython/bin/python setup.py install || exit 1

# Run tests
"$WORKSPACE"/vpython/bin/nosetests -v -v -w "$WORKSPACE"/gcovr \
    --with-xunit --xunit-file="$WORKSPACE"/TEST-gcovr.xml \
    || echo "(INFO) nosetests returned non-zero return code"

echo "DONE"

