#!/bin/bash

# testpyke [-p python_command] [ errorfiles_file ]
#
# no arguments.
#
# run in pyke source directory to test all doctests.
# 
# exit status > 0 if errors found.

ERRORFILES="/tmp/testpyke.$$"
TMPFILE="/tmp/testpyke2.$$"

PYTHON=python2.5

if [ $# -ge 2 -a "x$1" = x-p ]
then
    PYTHON="$2"
    shift 2
fi

> $ERRORFILES
NUM_ERRORS=0

for f in `find . -name '*.py' ! -name '*_[bf]c.py'`
do
    echo Testing "$f"
    if ! "$PYTHON" "$f"
    then
        echo "$f" >> $ERRORFILES
        NUM_ERRORS=$(($NUM_ERRORS + 1))
    fi
done

cd krb_compiler
echo Testing scanner_tables.py
if [ scanner.py -nt scanner_tables.py ]
then
    echo "krb_compiler/scanner_tables.py" >> $ERRORFILES
    NUM_ERRORS=$(($NUM_ERRORS + 1))
fi
echo Testing krbparser_tables.py
if [ scanner.py -nt krbparser_tables.py -o \
     krbparser.py -nt krbparser_tables.py ]
then
    echo "krb_compiler/krbparser_tables.py" >> $ERRORFILES
    NUM_ERRORS=$(($NUM_ERRORS + 1))
fi
echo Testing kfbparser_tables.py
if [ scanner.py -nt kfbparser_tables.py -o \
     kfbparser.py -nt kfbparser_tables.py ]
then
    echo "krb_compiler/kfbparser_tables.py" >> $ERRORFILES
    NUM_ERRORS=$(($NUM_ERRORS + 1))
fi

if [ $NUM_ERRORS -eq 0 ]
then
    echo Testing compiler.krb
    rm -rf compiled_krb
    if "$PYTHON" -c "from pyke import krb_compiler; krb_compiler.compile('compiled_krb', 'compiled_krb', ('compiler.krb',))"
    then
        # Ignore differences in Krb_filename from being compiled on different
        # boxes...
        diff compiler_bc.py compiled_krb/compiler_bc.py |
            sed '
                /^[0-9]*c[0-9]*$/d
                /^---$/d
                /^[<>] Krb_filename = /d
            ' > $TMPFILE
        if [ -s $TMPFILE ]
        then
            echo "krb_compiler/compiler.krb not compiled!" >> $ERRORFILES
            NUM_ERRORS=$(($NUM_ERRORS + 1))
        else
            rm -rf compiled_krb
        fi
    else
        echo "krb_compiler/compiler.krb" >> $ERRORFILES
        NUM_ERRORS=$(($NUM_ERRORS + 1))
    fi
fi

cd ..

if [ $NUM_ERRORS -eq 0 ]
then
    echo "No Errors!"
    rm -f $ERRORFILES
else
    echo "********** ERRORS ************* $NUM_ERRORS files had errors:"
    cat $ERRORFILES
    if [ $# -gt 0 ]
    then
        sed 's,^\.,pyke,' $ERRORFILES >> "$1"
    fi
    rm -f $ERRORFILES
    exit $NUM_ERRORS
fi
