#!/bin/sh

cd `dirname $0`

(test -d tests && test -x ocroscript) || {
    echo "This script must be run in the ocropus/ocroscript directory."
    exit 1
}

export OCROSCRIPTS=`pwd`/scripts
export OCROPUS_DATA=`pwd`/../data
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
ocroscript=`pwd`/ocroscript

cd tests

test -f $OCROPUS_DATA/models/neural-net-file.nn || {
    echo "I can't find $OCROPUS_DATA/models/neural-net-file.nn"
    exit 1
}

test -x $ocroscript || {
    echo "I can't find ocroscript."
    exit 1
}

$ocroscript -e 'print("# hello world from ocroscript")' || {
    echo "TEST FAILED: Somehow I can't run ocroscript at all."
    echo "I'm using: $ocroscript"
    exit 1
}

$ocroscript -e 'pcall(function () a=intarray(); a:at(1); end)' || {
    echo "TEST FAILED Your version of ocroscript cannot catch C++ exceptions."
    echo "You need to patch tolua++ or get a newer version of tolua++."
    echo "Do a touch *.pkg in ocropus/ocroscript after updating tolua++ and"
    echo "before running jam to make sure the binary gets updated properly."
    echo "This is a FATAL failure because many scripts rely on catching C++ exceptions."
    exit 1
}

$ocroscript -e 'pcall(function () fill(a,0) end)' || {
    echo "TEST FAILED your version of ocroscript segfaults on nil reference arguments."
    echo "You need to patch tolua++ or get a newer version of tolua++."
    echo "Do a touch *.pkg in ocropus/ocroscript after updating tolua++ and"
    echo "before running jam to make sure the binary gets updated properly."
}

if [ `ls images | grep png | wc -l` = "0" ]; then 
    echo "TEST FAILED Your test/images directory has no images."
    echo "Test images are distributed in a separate package,"
    echo "so look for it on http://www.ocropus.org"
fi

echo '# the following ocroscript invocations should produce no output'
bad=0
for i in test-*.lua; do 
	echo '#' ocroscript $i
        $valgrind $ocroscript  -e '
            ok,result = pcall(function() dofile("'$i'") end)
            if not ok then 
                print(result.." TEST FAILED UNEXPECTEDLY ('$i')") 
                os.exit(1)
            end
        ' /dev/null || bad=1
done

echo '# all tests done'
exit $bad
