#! /bin/sh -
#
# Script for testing the C Xoxa implementation against the
# collection of test files in $TOP/test/testcases/misc

if test -z "$FILETESTS"
then
    echo "$0: need to define FILETESTS, giving location of file test-cases" >&2
    exit 1
fi

PROG=../xoxa

verbose=${VERBOSE_TESTS=false}

# Test the identity transform using the identity_xoxa version
IDENTITY=./identity_xoxa

OUTDIR=file-tests.work
logfile=$OUTDIR/log

# Get the sha1 digest of a file
# (how portable is this openssl invocation?)
getsha () {
    openssl sha1 $1 | sed 's/^.*= *//'
}


test -d $OUTDIR || mkdir $OUTDIR

test_file() {
    norm=$1
    is_ok=:
    input=`echo $norm | sed 's/\.norm$//'`
    out=$OUTDIR/`basename $input`
    digest_option='-d sha1'
    if test -r $input.config; then
        . $input.config
    fi

    $verbose && echo $PROG $input.xml
    { $PROG $input.xml || echo "ERREXIT"; } >$out.out 2>$out.stderr
    # Simple test: check the output is identical to a nominal test file
    if diff $norm $out.out >$out.diff; then
        rm $out.out $out.stderr $out.diff
    else
        { echo
            echo "This was..."
            echo $PROG $input.xml
            echo "% diff $norm $out.out"
        } >>$out.diff
        echo "Test $out failed: diffs in $out.diff" >>$logfile
        is_ok=false
    fi

    # Identity test: check the (normalised) output of the identity program
    # is the same as the version without the identity program
    if $is_ok; then
        $verbose && echo $IDENTITY $input.xml \| $PROG
        { { $IDENTITY $input.xml | $PROG; } || echo "ERREXIT"; } >$out.out 2>$out.stderr
        if diff $norm $out.out >$out.diff; then
            rm $out.out $out.stderr $out.diff
        else
            { echo
                echo "This was..."
                echo $IDENTITY $input.xml \| $PROG
                echo "% diff $norm $out.out"
            } >>$out.diff
            echo "Test $out failed (identity check): diffs in $out.diff" >>$logfile
            is_ok=false
        fi
    fi

    digest_good=`cat $input.digest`
    $verbose && echo $PROG $digest_option -q $input.xml
    digest_test=`$PROG $digest_option -q $input.xml`
    if test "$digest_good" != "$digest_test"; then
        echo "Test $input failed digest: expected $digest_good, got $digest_test" >>$logfile
        is_ok=false
    fi

    $is_ok && return 0 || return 1
}

rm -f $logfile
touch $logfile

for f in $FILETESTS/*.norm
do
    if expr $f : '.*1.1' >/dev/null; then
        # skip this XML 1.1 file
        echo "Skipping XML 1.1 file $f" >&2
    else
        test_file $f || break
    fi
done

# Report the results
if test -s "$logfile"; then
    echo "FAIL: some xoxa tests failed (C), see $OUTDIR"
    cat $logfile
    status=1
else
    echo "OK: all xoxa file tests passed (C)"
    rm -Rf $OUTDIR
    status=0
fi

exit $status
