#!/bin/bash

# Description: Script that runs command-line tests
#
# Usage: build_and_run_all_cli_tests [jpeg2000] [pdf] [<Test1>] [<Test2>] ...
#
# where: jpeg2000 = run jpeg2000 test(s). Requires CONFIG+=jpeg2000 in qmake build
#        pdf      = run pdf test(s). Requires CONFIG+=pdf in qmake build
#        <Test#>  = specifies a selected test. If none are selected then all are run

# Test names. Specify a single test to run just that test
testsAvailable=( \
    TestCentipedeEndpoints \
    TestCorrelation  \
    TestCrc32 \
    TestExport \
    TestExportAlign \
    TestFitting \
    TestFormats \
    TestGraphCoords \
    TestGridLineLimiter \
    TestGuidelines \
    TestMatrix \
    TestProjectedPoint \
    TestSpline \
    TestSplineDrawer \
    TestTransformation \
    TestValidators \
    TestZoomTransition)

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

# Pass script arguments to qmake. Other arguments are interpretted as tests to be run
CONFIGARGS=""
testsSelected=()
while test $# -gt 0
do
    case "$1" in
        jpeg2000) CONFIGARGS="CONFIG+=jpeg2000 $CONFIGARGS"
            ;;
        pdf) CONFIGARGS="CONFIG+=pdf $CONFIGARGS"
             ;;
        *) testsSelected+=("$1")
    esac
    shift
done

selectedCount=${#testsSelected[@]}
if [ $selectedCount -eq 0 ]; then
    testsSelected=(${testsAvailable[*]})
fi

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

if [ $selectedCount -eq 1 ]
then
    echo
    echo "Since a single test is selected, engauge_test.pro will not be deleted so the code can be easily rebuilt and debugged"
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

# 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
echo "Rebuilding..."

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

    # Exit immediately on first error
    set -e 

    # Build and run each test
    for t in "${testsSelected[@]}"
    do
        sed "s/TEST/$t/g" engauge_test_template.pro >engauge_test.pro
        qmake6 $CONFIGARGS engauge_test.pro
        make -j4 all || {
            echo "FAIL   : Compilation error, testing will be stopped"
            exit 1
        }
        # sed is used to add color to PASS and FAIL. 'Using QtTest' lines are dropped
        ../bin/$t | sed "s/PASS   :/$(tput setaf 2)PASS$(tput sgr0)   :/" | sed "s/FAIL   :/$(tput setaf 1)FAIL$(tput sgr0)   :/" | grep -v 'Using QtTest'
        if [ $selectedCount -ne 1 ]
        then
            rm engauge_test.pro
        fi
    done
fi
