#! /bin/bash

OPTIONS=""
ARGUMENTS=""
INCLUDES="."

HELPEXITCODE="1"

for arg in $@;
do
    case $arg in
        -h)
            HELP="true"
            HELPEXITCODE="0";;
        -v)
            VERBOSE="true";;
        -B*)
            BASEDIR=${arg:2};;
        -I*)
            INCLUDES=${arg:2}:${INCLUDES};;
        -J*)
            JARPATH=${arg:2};;
        -*)
            OPTIONS="${arg} ${OPTIONS}";;
        *)
            ARGUMENTS="${ARGUMENS} $arg";;
    esac
done

if [ -z "$ARGUMENTS" ];
then
    HELP="true"
fi

if [ -n "$HELP" ];
then
    cat 1>&2 << EOF
$0 [options] datalog_source_file

        Options:
-h
            Print out this help description.
-v
            Invoke bddbddb with verbose output.
-Bdirectory
            The specified directory contains program relations.
-Idirectory
            The specified directory contains datalog source files.
            This option may be used many times for multiple directories.
-Jdirectory
            The specified directory constains bddbddb's jar files.

Other options are passed directly to the java vm and bddbddb if they
do not collide with the options specified above.

EOF
    exit $HELPEXITCODE
fi

if [ -z "$BASEDIR" ];
then
    BASEDIR="./dump"
fi

INCLUDES="$BASEDIR:$INCLUDES"

if [  -z "$JARPATH" ]
then
    JARPATH="`dirname $0`/jars"
fi

for jar in `find $JARPATH -iname '*.jar' 2> /dev/null`;
do
    if !(echo $CLASSPATH | grep "$jar" > /dev/null);
    then
        export CLASSPATH="$CLASSPATH:$jar"
    fi
done

for jar in bddbddb.jar javabdd-2.0.jar jdom.jar jwutil-1.0.jar weka.jar;
do
    if !( echo $CLASSPATH | egrep "$jar" > /dev/null);
    then
        cat 1>&2 << EOF
$jar not found in CLASSPATH
EOF
        JARNOTFOUND="true"
    fi
done

if [ -n "$JARNOTFOUND" ];
then
    exit 1
fi

if [ -n "$VERBOSE" ];
then
    FILTER="cat"
else
    FILTER='egrep -A1000 "^Saving results: Tuples in query" -'
fi

echo "java -Dbasedir=${BASEDIR} -Dincludedirs=${INCLUDES} -Xms1024m -Xmx1024m ${OPTIONS} net.sf.bddbddb.BDDSolver ${ARGUMENTS} 2>&1 | sh -c ${FILTER}"
java -Dbasedir=${BASEDIR} -Dincludedirs=${INCLUDES} -Xms1024m -Xmx1024m ${OPTIONS} net.sf.bddbddb.BDDSolver ${ARGUMENTS} 2>&1 | sh -c "${FILTER}"

