#!/bin/sh

# Note:  When run via "make check", test output files are automatically deleted.
#	 When run from the command line, output files are left in directory
#	 grftest.YYYYMMDD.  This is useful when something is different.
#
#	 ./inputs  - test inputs
#	 ./outputs - known correct outputs
#		     esp. grftest.out
#
#	 grftest.YYYYMMDD:
#		directory containing individual output files

NODB=1 . ${srcdir=.}/t.frame

# Fisher config
cat <<EOF > "$TMPDIR"/cfg.f
robx=0.415
min_dev=0.1
ham_cutoff=0.0
EOF

# Fisher tristate
cat <<EOF > "$TMPDIR"/cfg.t
robx=0.415
min_dev=0.1
ham_cutoff=0.1
terse_format = %1.1c %d
spamicity_tags = s,h,u
spamicity_formats = %0.6f %0.6f %0.6f
EOF

V="v"	# verbosity level

map_rc()
{
    (
	set +e
	"$@"
	a=$?
	[ $a -eq 0 ] && exit 0
	[ $a -eq 1 ] && exit 0
	[ $a -eq 2 ] && exit 0
	exit $a
    )
}

run_test()
{
    id="$1"
    fil="$2"
    ver="$3"
    OUT="$TMPDIR"/tests/msg.$fil.$mth.$ver
    OPTS="-t -$ver -y 0"
    map_rc $BOGOFILTER $OPTS -c "$TMPDIR"/cfg.$mth < "$SYSTEST/inputs/msg.$id.txt" > "$TMPDIR/tests-$mth"
    sed 's/,.version=.*//' < "$TMPDIR/tests-$mth" > "$OUT"
}

if [ -d "$TMPDIR"/tests ] ; then rm -f "$TMPDIR/tests/"* ; else : ; fi
mkdir -p "$TMPDIR/tests"

for mth in f t ; do
    BOGOFILTER_DIR="$TMPDIR"/words.$mth
    CFG="-y 0"
    export BOGOFILTER_DIR
    if [ -d "$BOGOFILTER_DIR" ] ; then rm -f "$BOGOFILTER_DIR"/* ; else : ; fi
    mkdir -p "$BOGOFILTER_DIR"
    $BOGOFILTER -y 0 -c "$TMPDIR/cfg.$mth" -s < "$SYSTEST/inputs/spam.mbx"
    $BOGOFILTER -y 0 -c "$TMPDIR"/cfg.$mth -n < "$SYSTEST/inputs/good.mbx"
    for f in "$BOGOFILTER_DIR"/*.$DB_EXT ; do
	n=`basename "$f" .$DB_EXT`
	$BOGOUTIL -d "$BOGOFILTER_DIR/$n.$DB_EXT" > "$BOGOFILTER_DIR/$n.txt"
    done
#   [ $verbose -gt 0 ] && $BOGOUTIL -w $BOGOFILTER_DIR .MSG_COUNT
    #
    # run tests for msg.[1-8].txt
    #
    for msg in "$SYSTEST/inputs/"msg.?.txt ; do
	tst=`echo "$msg" | sed "s@$SYSTEST/inputs/msg.@@" | sed 's@.txt@@'`
	args="$tst $tst $V"
	run_test $args
    done
done

OUT="grftest.out"

printf "%2s     %-10s   %-10s\n" id fisher tristate > "$TMPDIR/tests/$OUT"
for out in "$TMPDIR"/tests/msg.?.t.$V ; do
    id=`echo "$out" | sed "s@$TMPDIR/tests/msg.@@" | sed "s@.t.$V@@"`
    f=`head -1 "$TMPDIR"/tests/msg.$id.f.$V | tr "HS" "hs"`
    t=`head -1 "$TMPDIR/tests/msg.$id.t.$V"`
    printf "%2s   %c %s   %c %s\n" $id $f $t >> "$TMPDIR"/tests/$OUT
done

if [ "$BF_SAVEDIR" ] ; then . "$srcdir"/t.save ; fi


if  [ $verbose -eq 0 ]; then
    cmp "$OUTPUTS"/$OUT "$TMPDIR"/tests/$OUT
else
    diff $DIFF_BRIEF "$OUTPUTS"/$OUT "$TMPDIR"/tests/$OUT
fi
