#!/bin/bash
# test script to test TOPCOM clients:

PATH=/bin:/usr/bin:../src/:../src-reg

testdatadir="testdata"

srcdir=$1
builddir=$2
testfile=$3
testbasename=${testfile##*/}
srctestfile=${srcdir}/${testdatadir}/${testbasename}

echo "******************************************************************************"
echo "* TOPCOM test script"
echo "* $0"
echo "* was called with the following data:"
echo "*----------------------------------------------------------------------------*"
echo "*             builddir is:" $builddir
echo "*               srcdir is:" $srcdir
echo "*             testfile is:" $testfile
echo "* basename of testfile is:" $testbasename
echo "*          srctestfile is:" $srctestfile
echo "******************************************************************************"

echo testing ${srctestfile} ...

# the following seems to be unnecessary since
# automake generates $(testdatadir)
# and takes the tests from $(srcdir)
# allthough the targets are prefixed by $(builddir);
# it is kept here in case this changes in the future:
if [ ! "$srcdir" = "$builddir" ]
then
    if [ ! -d "${builddir}/${testdatadir}" ]
    then
	echo making directory "${builddir}/${testdatadir}" for logs ...
	mkdir "${builddir}/${testdatadir}"
	echo ... done
    else
	echo directory "${builddir}/${testdatadir}" exists
    fi
fi

contents=`cat $srctestfile | tr -d '\n'`

echo stripped test file contains:
echo $contents

IFS='|'
read -r client inputfile options resultfile <<_EOF_
$contents
_EOF_

echo "client is     :" $client
echo "input file is :" $inputfile
echo "options are   :" $options
echo "result file is:" $resultfile

resultpath=${srcdir}/${testdatadir}/${resultfile}

if [ ! -f $resultpath ]
then
    echo $resultpath not found - FAILURE
    exit 1
fi

if [ -z $inputfile ]
then
    input=""
else
    inputpath=${srcdir}/${testdatadir}/${inputfile}
    if [ ! -f $inputpath ]
    then
	echo $inputpath not found - FAILURE
	exit 1
    else
	input="-i $inputpath"
    fi
fi

commandline="$client $input $options"
echo checking "$client" against "$resultfile" using "$commandline"
testresult=`sh -c "$commandline" | tr -d '\n' | tr -d ' '`
# echo ... done.

# echo test result is $testresult

if [ -z $testresult ]
then
    echo $commandline produced no output - FAILURE 
    exit 1
fi

# echo reading known result from result file "$resultfile" ...
knownresult=`cat $resultpath | tr -d '\n' | tr -d ' '`
# echo $knownresult
# echo ... done.

# echo ... comparing with known result from "$resultfile ..."
if [ "$testresult" = "$knownresult" ]
then
    echo PASS
    exit 0
else
    echo $commandline produced
    echo $testresult
    echo while expected result is
    echo $knownresult
    echo FAILURE
    exit 1
fi
#eof test script
