#!/bin/sh

PROLOG=prolog
PROLOG_WITH_ORACLE=prolog

PATH=/usr/5bin:/usr/bin:/bin:$PATH
export PATH

USAGE="Usage: check_timedb -o -e user/passwd file(s)\n\
               \t-o uses ORACLE to do comparison\n\
               \t-e uses the emulator to do comparison (default)\n\
               \t!! database 'user/passwd' is erased\n\
               \t!! verify \$TIMEDB_HOME, and \$ORACLE_EMULATOR"

if test $# -lt 2
then
  echo $USAGE
  exit
fi

############### option & argument handling

emulator=false
oracle=false

while getopts oeh opt
do
  case $opt in 
    e) emulator=true;;
    o) oracle=true;;
    h) echo $USAGE; exit
  esac
done
shift `expr $OPTIND - 1`

if test $oracle = false
then
  prolog=$PROLOG
  backendOpt=-e
else
  prolog=$PROLOG_WITH_ORACLE
  backendOpt=-o
fi

login=$1
shift 1
whichfiles=$*

if test $whichfiles = all
then
  files=demo??
else
  files=$whichfiles
fi

start_dir=$PWD

############### verifying test file(s)

for f in $files
do
  cd $TIMEDB_HOME
  initdb $backendOpt $login
  cd $start_dir
  date
  echo "Differences found running '$f' against the reference file:"
  echo "-------------------------------------------------------------"
  grep '^[^#]' $f |\
  sed "1 i\\
     consult('$TIMEDB_HOME/timeDB.pl').\\
     open '$login';\\
     batch '$TIMEDB_HOME/../Demos/$f.in' '$TIMEDB_HOME/../Demos/$f.out';" |\
  sed "$ a\\
     quit;\\
    " |\
  $PROLOG 1>$f.out 2>/dev/null -a $backendOpt -t -s
  sed -e 's/[ .]//g'\
      -e '/^-$/d'\
      -e '/^$/d'\
      -e '/MET/d'\
      -e '/{loading/d'\
      -e '/{consulting/d'\
      -e '/{compiling/d' \
      -e '/{Undefined/d' \
      -e '/msec/d' \
      -e '/{TimeDB/d' \
      -e '/{Andreas/d' \
      -e '/Databaseopened/d' \
      -e '/^$/d'         $TIMEDB_HOME/../Demos/$f.out > $TIMEDB_HOME/../Demos/tmp.out
  sed -e 's/[ .]//g'\
      -e '/^-$/d'\
      -e '/MET/d'\
      -e '/{loading/d'\
      -e '/{consulting/d'\
      -e '/{compiling/d' \
      -e '/{Undefined/d' \
      -e '/msec/d' \
      -e '/{TimeDB/d' \
      -e '/{Andreas/d' \
      -e '/Databaseopened/d' \
      -e '/^$/d'         $TIMEDB_HOME/../Demos/$f.ref > $TIMEDB_HOME/../Demos/tmp.ref
  diff tmp.out tmp.ref
  echo "End of list of differences found when checking file '$f'"
  echo "-----------------------------------------------------------"
  date
done

rm $TIMEDB_HOME/../Demos/tmp.out $TIMEDB_HOME/../Demos/tmp.ref

exit 0

