#!/bin/bash

TEST="./test_kmime_codec"
#BUFFER_SIZES="$(seq 7)"
#BUFFER_SIZES="$(seq 5) 15 16 17 23 24 25 31 32 33 4096"
BUFFER_SIZES="$(seq 17) 23 24 25 31 32 33 4096"
USAGE_PATTERNS="chunkwise kio"

oldDirName=""
encoding=""
action=""
inFile=""
resultFile=""

totalTests=0
passedTests=0
failedTests=0

# loop over all .expected files in the directory
# specified by the single argument:

for i in $(find "$@" -type f -name '*.expected'); do
	dirName="$(dirname "$i")"
	if [ "$dirName" != "$oldDirName" ]; then
		oldDirName="$dirName"
		# new directory: extract encoding
		encoding="$(basename "$dirName")"
		encoding="${encoding#codec_}"
		echo Entering directory \"$dirName\".
		echo Using encoding \"$encoding\".
	fi

	testName="$(basename "$i")"
	testName="${testName%.expected}"
	echo "testName=$testName"
	inFile="$dirName/$testName"
	echo "inFile=$inFile"
	if [ "${testName%.$encoding}" != "$testName" ]; then
		testName="${testName%.$encoding}"
		action="--decode"
	else
		#testName stays the same
		action="--encode"
	fi
	resultFile="$dirName/$testName.result"
	echo "resultFile=$resultFile"
	echo performing ${action#--} test \"$testName\"
	for usagePattern in $(echo $USAGE_PATTERNS); do
	    for insize in -1 $(echo $BUFFER_SIZES); do
		for outsize in $(echo $BUFFER_SIZES); do
		    let "totalTests++"
		    if [ "$insize" == "-1" ]; then
			#omit --input-buffer-size
			$TEST $action $encoding \
			    --usage-pattern $usagePattern \
			    --output-buffer-size $outsize \
			    --outfile "$resultFile" \
				      "$inFile" \
			> /dev/null 2> /dev/null
		    else
			$TEST $action $encoding \
			    --usage-pattern $usagePattern \
			    --input-buffer-size $insize \
			    --output-buffer-size $outsize \
			    --outfile "$resultFile" \
				      "$inFile" \
			> /dev/null 2> /dev/null
		    fi
		    result=$?
		    case $result in
		    0)
			if cmp "$i" "$resultFile" >/dev/null 2>/dev/null ; then
			    let "passedTests++"
			else
			    let "failedTests++"
			    mv "$resultFile" "$resultfile.failed.$usagePattern.$insize-$outsize"
			fi
		    ;;
		    *)
			let "failedTests++"
			mv "$resultFile" "$resultFile.failed.$usagePattern.$insize-$outsize-$result" || touch "$resultFile.failed.$insize-$outsize-$result"
		    ;;
		    esac
		    rm -rf "$resultFile"
		done
	    done
	done
	if [ $totalTests != $passedTests ]; then
		echo "some tests failed."
	fi
done

echo "TOTAL: $totalTests; PASSED: $passedTests; FAILED: $failedTests;"
