#!/bin/bash
# Uncomment next line to print each bash command before it is executed
#set -x

echo "Job $CI_JOB_NAME"

if ! grep -q TRIGGER_STAGE_TEST "${PROJECT_LOG_DIR}/trigger-stage.txt"; then
    echo "Job skipped as /test flag not in commit message and CAMITK_CI_STAGE < $STAGE_CONFIGURE"; 
    exit 1;
fi

echo "===== test ====="


if [[ "$osName" != "win7" ]]; then
    echo "===== Configuring xvfb ====="
    # Starts the server first (try to avoid unexpected and random "QXcbConnection: Could not connect to display :99")
    # see also https://doc.qt.io/qt-5/embedded-linux.html#linuxfb 
    export DISPLAY=":98"
    #-ac +extension GLX +render -noreset -v -fbdir $workingDir/ &> ${PROJECT_LOG_DIR}/test.log &
    Xvfb $DISPLAY -screen 0 1600x1200x24 &> ${PROJECT_LOG_DIR}/test.log &
    trap "kill $! || true" EXIT
    sleep 10
    export XAUTHORITY=/dev/null
fi

ctest -VV \
      -DCTEST_SITE="$CDASH_SITE" \
      -DCI_MODE="$CAMITK_CI_MODE" \
      -DCI_ID="P $CI_PIPELINE_ID - J $CI_BUILD_ID" \
      -DCI_BRANCH="$CI_COMMIT_REF_NAME" \
      -DCI_BUILD_SETTINGS="$COMPILER_CONFIG" \
      -DCI_PROJECT_LOG_DIRECTORY="$CI_PROJECT_DIR/$PROJECT_LOG_DIR" \
      -DCTEST_SOURCE_DIRECTORY="$PROJECT_SOURCE_DIR" \
      -DCTEST_BINARY_DIRECTORY="$PROJECT_BUILD_DIR" \
      -S $PROJECT_SOURCE_DIR/sdk/cmake/ctest/ci-test.cmake > >(tee ${PROJECT_LOG_DIR}/test.log | grep --line-buffered -e "Test \#") 2>&1


# if [[ "$OS" != "win7" ]]; then
#     # shutdown xvfb
#     kill $xvfbPid
# fi

# as ctest return a strange 255 error, check the log
if grep --quiet "Fatal error" $CI_PROJECT_DIR/$PROJECT_LOG_DIR/ci-test.log; then
    echo "Found fatal error in $CI_PROJECT_DIR/$PROJECT_LOG_DIR/ci-test.log"
    exit 1
else
    echo "OK"
fi
