#!/bin/sh

# This is analyzer of output of standard-formed tests
# Requires variables: LAUNCH_EXIT_CODE, STDOUT_FN, STDERR_FN
# Produces variables: SUBTEST_COUNT, TEST_PASSED, RESULT_COMMENT, ERROR_LEVEL
# Produces functions: analyze_subtest

SUBTEST_COUNT=`grep -E 'complete|\*\*\*error' <"$STDOUT_FN" | wc -l`

if [ `grep -E 'Assertion' <"$STDERR_FN" | wc -l` -gt 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="Assertion failed"
    ERROR_LEVEL=5
elif [ `grep -E 'RTS fatal' <"$STDERR_FN" | wc -l` -gt 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="RTS fatal"
    ERROR_LEVEL=4
elif [ `grep -E 'RTS err' <"$STDERR_FN" | wc -l` -gt 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="RTS err"
    ERROR_LEVEL=3
elif [ `grep "END OF" <"$STDOUT_FN" | wc -l` -eq 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="Crash"
    ERROR_LEVEL=2
elif [ $LAUNCH_EXIT_CODE -ne 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="Launch failure"
    ERROR_LEVEL=6
elif [ `grep '\*\*\*error' <"$STDOUT_FN" | wc -l` -gt 0 ]; then
    TEST_PASSED=0
    RESULT_COMMENT="Has failed subtests"
    ERROR_LEVEL=1
else
    TEST_PASSED=1
    RESULT_COMMENT="OK"
    ERROR_LEVEL=0
fi

analyze_subtest() {
    # Produces variables: SUBTEST_NAME, TEST_PASSED, RESULT_COMMENT, ERROR_LEVEL
    local SUBTEST_LINE=`grep -E 'complete|\*\*\*error' <"$STDOUT_FN" | head -n $1 | tail -n 1`
    SUBTEST_NAME=`echo "$SUBTEST_LINE" | awk '{print $1}'`
    if [ `echo $SUBTEST_LINE | grep "complete" | wc -l` -eq 0 ]; then
        TEST_PASSED=0
        RESULT_COMMENT="Subtest failed"
        ERROR_LEVEL=1
    else
        TEST_PASSED=1
        RESULT_COMMENT="OK"
        ERROR_LEVEL=0
    fi
}
