#!/bin/sh

[ -e PKG_ADD ] && mv PKG_ADD PKG_ADD.bak

echo Checking package...

unit_test_regex='^%!\(assert\|test\|error\|fail\|xtest\|warning\)'

# Extract tests from installed m files
echo Checking m files ...
tmp=$(tempfile)
echo "addpath (genpath ([pwd(),'/debian']));" > $tmp
echo "pkg load all;" >> $tmp
for f in $(find debian/ -name \*.m $excluded_files_expr	| grep -v /private/) ; do
    if grep -q "$unit_test_regex" $f ; then
        stem=$(echo $f | sed 's:[^@]*/::;s/\.m$//')
	echo "disp (\"[$stem]\")" >> $tmp
        echo "test $stem $OCTPKG_TEST_OPT" >> $tmp
    fi
done
$OCTPKG_TEST_ENV $octave $octave_options $tmp
rm -f $tmp

# Extract tests from .cc files - these are not installed, but the
# compiled .oct files are.
# We search for the tests in the .cc files, but invoke the .oct files;
# this means we must add generate a loadpath starting at the current
# directory and source PKG_ADD files (they might add autoload()
# directives)

# We deactivate the warning about relative paths used for the PKG_ADD file.
echo Checking CC files ...
tmp=$(tempfile)
echo "addpath (genpath ([pwd()], '.pc'));" >> $tmp
echo "pkg load all;" >> $tmp
echo "warning ('off', 'Octave:autoload-relative-file-name');" >> $tmp
if [ -f PKG_ADD ] ; then
    echo "source('PKG_ADD');" >> $tmp
fi
if [ -f PKG_ADD.bak ] ; then
    echo "source('PKG_ADD.bak');" > $tmp
fi
if [ -d src ] ; then
    for f in $(find src/ -name \*.cc $excluded_files_expr) ; do
        if grep -q "$unit_test_regex" $f ; then
            stem=${f%%.cc}
            stem=${stem##*/}
            echo "disp (\"[$stem]\")" >> $tmp
            echo "test $stem $OCTPKG_TEST_OPT" >> $tmp
        fi
    done
fi
$OCTPKG_TEST_ENV $octave $octave_options $tmp
rm -f $tmp

if [ -f debian/check.m ] ; then
    $OCTPKG_TEST_ENV $octave $octave_options --eval	\
        "addpath (genpath ([pwd(),'/debian']));		\
         pkg load all;					\
         source ('debian/check.m');"
fi

if [ -e PKG_ADD.bak ] ; then
    mv PKG_ADD.bak PKG_ADD
fi
