#!/bin/bash

# Description: Script that runs command-line tests
#
# Usage: build_and_run_all_cli_tests [jpeg2000] [pdf]
#
# where: jpeg2000 = run jpeg2000 test(s). Requires CONFIG+=jpeg2000 in qmake build
#        pdf      = run pdf test(s). Requires CONFIG+=pdf in qmake build

# Test names. Specify a single test to run just that test
tests=( \
    TestCorrelation  \
    TestExport \
    TestFormats \
    TestGraphCoords \
    TestGridLineLimiter \
    TestMatrix \
    TestProjectedPoint \
    TestSegmentFill \
    TestSpline \
    TestTransformation \
    TestValidators)

echo "Available tests: " ${tests[*]}

# Pass script arguments to qmake
CONFIGARGS=""
while test $# -gt 0
do
    case "$1" in
	jpeg2000) CONFIGARGS="jpeg2000 $CONFIGARGS"
	    ;;
        pdf) CONFIGARGS="pdf $CONFIGARGS"
            ;;
    esac
    shift
done

if [ -n "$CONFIGARGS" ]; then
    CONFIGARGS="CONFIG+=$CONFIGARGS"
fi

# Need gcc 4 at /C/cygwin/bin rather than gcc 3 at /usr/bin to prevent 'unrecognized command line
# option -fno-keep-inline-dllexport'
PATH=/C/QtOpenSource/Qt5.5.1/Tools/mingw492_32/bin:$PATH
argcount="$#"

if [ $argcount -gt 0 ]
then 
    tests=("$@");
fi

echo "Selected tests: " ${tests[*]}

if [ $argcount -eq 1 ]
then
    echo "Since a single test is selected, engauge_test.pro will not be deleted so the code can be easily rebuilt and debugged"
fi

# Logging
LOGFILE="build_and_run_all_cli_tests.log"
rm -rf $LOGFILE
echo "Afterwards, check $LOGFILE to verify success"

# Cleanup. We do not want to force complete rebuild for each test application since that takes VERY long
rm .moc_test/* 2>/dev/null
rm .objs_test/* 2>/dev/null
rm ../bin/Test* 2>/dev/null
echo "Rebuilding..."

# Make sure correct qt installation is being used, by looking for '5.' in the version number
VERSION5=`qmake -v | grep '5\.'`
if [ -z "$VERSION5" ]
then
    echo "Need Qt5";
else

    # Exit immediately on first error
    set -e 

    # Build and run each test
    for t in "${tests[@]}"
    do
	sed "s/TEST/$t/g" engauge_test_template.pro >engauge_test.pro
	qmake $CONFIGARGS engauge_test.pro
	make all 2>>$LOGFILE >/dev/null
	../bin/$t
	if [ $argcount -ne 1 ]
	then
            rm engauge_test.pro
	fi
    done
fi
