#!/usr/bin/env bash
#
# Copyright IBM Corp. 2017
#
# Usage: testsuite_exit
#
# Announce end of test suite and show aggregate results.
#

TOPDIR=$(readlink -f $(dirname $0)/..) && test -d "$TOPDIR" \
    && source "$TOPDIR/bin/common"

echo "end_time $(date +%s.%N)" >>"$COUNTFILE"

SUCCESS=0
FAILED=0
SKIPPED=0
TOTAL_TIME=0
TOTAL_MEM=0
HAVE_EXT=0

# Get results
while read LINE ; do
	set -- $LINE
	case "$1" in
	start_time)	START_TIME=$2 ;;
	end_time)	END_TIME=$2 ;;
	pass)		let SUCCESS=$SUCCESS+1 ;;
	fail)		let FAILED=$FAILED+1 ;;
	skip)		let SKIPPED=$SKIPPED+1 ;;
	elapsed)	let TOTAL_TIME=$TOTAL_TIME+$3 ; HAVE_EXT=1 ;;
	resident)	let TOTAL_MEM=$TOTAL_MEM+$3 ; HAVE_EXT=1 ;;
	esac
done < "$COUNTFILE"

exec 3>&1
exec >>"$LOGFILE" 2>&1

t_marker
t_detail "DATE" "$(t_timestamp)"

let TOTAL=$SUCCESS+$SKIPPED+$FAILED
t_detail "EXECUTED" "$TOTAL"
t_detail "PASSED" "$SUCCESS"
t_detail "FAILED" "$FAILED"
t_detail "SKIPPED" "$SKIPPED"
[ $HAVE_EXT -eq 1 ] && t_detail "TIME" "${TOTAL_TIME}ms"
[ $HAVE_EXT -eq 1 ] && t_detail "MEM" "${TOTAL_MEM}kB"

TOTAL_TIME=$(($TOTAL_TIME/1000)).$(($TOTAL_TIME%1000/100))
TOTAL_MEM=$(($TOTAL_MEM/1024)).$((($TOTAL_MEM%1024)/100))
TOTAL="$BOLD$TOTAL tests executed$RESET"
PASS="$SUCCESS passed"
FAIL="$FAILED failed"
SKIP="$SKIPPED skipped"
TIME="time ${TOTAL_TIME}s"
MEM="mem ${TOTAL_MEM}MB"

[ "$SUCCESS" -gt 0 ] && PASS="$GREEN$PASS$DEFAULT"
[ "$FAILED"  -gt 0 ] && FAIL="$RED$FAIL$DEFAULT"
[ "$SKIPPED" -gt 0 ] && SKIP="$BLUE$SKIP$DEFAULT"

printf "$TOTAL, $PASS, $FAIL, $SKIP$RESET" >&3
[ $HAVE_EXT -eq 1 ] && echo -n " ($TIME, $MEM)" >&3
echo >&3
echo "Result log stored in $LOGFILE" >&3

if [ "$FAILED" -gt 0 ] ; then
	exit 1
fi

exit 0
