#!/bin/bash
# Test script helper functions
# M.Tyler 2015-10-24



OUT=tmp
VALG_LOGFILE=valg_log.txt
SHEXE=scripts

echo



case "$VALG" in
"Y" )	PROGPREFIX="valgrind --leak-check=full --show-possibly-lost=no"
	;;
"T" )	PROGPREFIX="/usr/bin/time"
	;;
*)	unset PROGPREFIX
	;;
esac


export LANG=C

# On error exit
#set -e
# On error don't exit
set +e

> $VALG_LOGFILE



run_sh()
{
	if [ "$1" != "" ]
	then
		echo $1
	fi

	shift

	$PROGPREFIX "$@" 2>>$VALG_LOGFILE
}

txt_title()
{
	printf "\n\e[100m\e[97m%25s %s %25s\e[0m\n\n" "" "$1"
}

txt_pass()
{
	printf "\e[94m%-25s PASS\e[0m\n" "$1"
}

txt_fail()
{
	printf "\e[41m\e[97m%-25s FAIL\e[0m\n" "$1"
}

cmp_arg()
{
	if [ "$2" = "$3" ]
	then
		txt_pass "$1"
	else
		txt_fail "$1"
	fi
}

cmp_diff()
{
	echo
	echo Comparing with checked results ...
	echo

	unset DIFF

	diff -Nurp "$2" "$3" && DIFF=1

	cmp_arg "$1" "$DIFF" "1"

	unset DIFF
}

cmp_bin()
{
	echo
	echo Comparing with checked results ...
	echo

	unset DIFF

	cmp "$2" "$3" && DIFF=1

	cmp_arg "$1" "$DIFF" "1"

	unset DIFF
}

run_sh_fail()
{
	# Check that this command fails

	TXT=$1
	shift
	FAIL=1

	$PROGPREFIX "$@" 2>>$VALG_LOGFILE && FAIL=0

	cmp_arg "$TXT" "$FAIL" "1"
}

run_sh_head()
{
	echo ----------- $FILE_SH -----------
	echo ----------- $FILE_SH ----------- >> "$1"
	echo >> $1
}

run_sh_tail()
{
	echo
	echo >> $1
	echo >> $1
}

run_sh_cli_init()
{
	LOGFILE=output/log.txt
	> $LOGFILE
}

run_sh_valg()
{
	run_sh_head $VALG_LOGFILE
	$PROGPREFIX $CLICOM < $1 >> $VALG_LOGFILE 2>&1
	run_sh_tail $VALG_LOGFILE
}

run_sh_normal()
{
	run_sh_head $LOGFILE
	$CLICOM < $1 >> $LOGFILE 2>&1
	run_sh_tail $LOGFILE
}

run_sh_cli()
{
	while [ -n "$1" ]
	do
		FILE_SH=$SHEXE/$1.txt

		case "$VALG" in
		"T" )
			;&
		"Y" )
			run_sh_valg $FILE_SH
			;;
		esac

		run_sh_normal $FILE_SH

		shift
	done
}

valg_results()
{
	case "$VALG" in
	"Y" )
		# Valgrind summary
		# Using Valgrind creates numerical differences in formula results
		# on my system which renders a 'diff' test useless.

		echo
		grep "definitely lost" $VALG_LOGFILE

		echo
		grep "ERROR SUMMARY" $VALG_LOGFILE
		;;
	"T" )
		# Memory usage

		echo
		grep "maxresident" $VALG_LOGFILE
		;;
	esac
}

