#!/bin/sh -x

# only run this when valgrind is in the path, skip otherwise
# ("exit 77" = skip)
#
# this is a stripped-down version of t.grftest

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

if test "x$BF_RUN_VALGRIND" = x ; then
    echo >&2 "----> the following test is skipped, set BF_RUN_VALGRIND=1 to run it"
    exit 77
fi

if test "x$EXE_EXT" = "x_static"; then
    exit 77
fi

case `valgrind --version` in
    valgrind-3*)
	VG_SUPP="$TMPDIR"/.valgrind.suppress
	VALGRIND="$VALGRIND 3>$TMPDIR/vg.out --log-fd=3"
	;;
    valgrind-2*)
	VG_SUPP="$TMPDIR"/vg.supp
	VALGRIND="$VALGRIND 3>$TMPDIR/vg.out --logfile-fd=3"
	;;
    *)
	exit 77
esac

( eval "$VALGRIND true" ) 2> /dev/null || exit 77
if ( eval "$VALGRIND false" ) 2> /dev/null ; then exit 77 ; fi

# 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 = %6.2e %6.2e %0.6f
EOF

# suppress valgrind complaints about glibc::strchr.S

cat <<EOF > "$VG_SUPP"
{
   ignore strchr problem
   Memcheck:Cond
   fun:strchr
}
EOF

#V="-v"	# verbosity level

run_test()
{
    tst="$1"
    IN="$SYSTEST/inputs/msg.$tst.txt"
    OT="$TMPDIR/msg.$tst.$mth"
    if [ -n "$V" ] ; then OT="$OT.$V" ; fi
    OPTS="-e -t $V $CFG"
    eval $VALGRIND --suppressions=${VG_SUPP} $BOGOFILTER $OPTS < $IN > $OT
    if test -s "$TMPDIR"/vg.out ; then cat "$TMPDIR"/vg.out ; exit 2 ; fi
}

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 "$CFG" -c "$TMPDIR"/cfg.$mth -s < "$SYSTEST"/inputs/spam.mbx
    $BOGOFILTER "$CFG" -c "$TMPDIR"/cfg.$mth -n < "$SYSTEST"/inputs/good.mbx
#   if [ $verbose -gt 0 ] ; then $BOGOUTIL -w $BOGOFILTER_DIR .MSG_COUNT ; fi

    for tst in 3 ; do
	run_test $tst
    done

done

rm $VG_SUPP
