#!/bin/sh

D=test.d
TESTENTRY=99
export D TESTENTRY

if ! [ -s ./startalk ]
then
  echo "Startalk not built yet.  Run make first."
  exit 201
fi

if [ $# -eq 0 ]
then
  echo "NOTE: This will only run tests that do not write to the phonebook."
  echo "      To run all tests, run $0"
  echo "        with the -overwrite switch (this only attempts to overwrite entry 99)"
  echo "      To suppress this warning, and still only run the read tests,"
  echo "        use the -nooverwrite switch."
  echo
fi

while echo "$1" |grep "^-" >/dev/null 2>&1
do
  if [ $1 = "-overwrite" ]
  then
    tests="`echo $D/[0-7][0-9]`"
  elif [ $1 = "-destructive" ]
  then
    tests="`echo $D/[0-9][0-9]`"
  elif [ $1 = "-nooverwrite" ]
  then
    :
  else
    echo "Unknown option '$1'"
    exit 200
  fi
  shift
done

if [ $# -eq 0 ]
then
  if [ -z "$tests" ]
  then
    tests="`echo "$D"/[0-4][0-9]` $tests"
  fi
  set $tests
fi

havewritten=0
haveread=0
failures=0
successes=0
for i in "$@"
do
  testnum=`basename "$i"`
  rm -f "$D"/$testnum.test

  echo -n "$testnum..."

  if echo "$testnum" |grep "^[3-4]" >/dev/null 2>&1 && [ "$haveread" -eq 0 ]
  then
    if [ $failures -gt 0 ]
    then
      echo "Aborted...Won't try any phone test unless all parsing tests succeed."
      exit $failures
    else
      haveread=1
    fi
  fi

  if echo "$testnum" |grep "^[5-9]" >/dev/null 2>&1 && [ "$havewritten" -eq 0 ]
  then
    if [ $failures -gt 0 ]
    then
      echo "Aborted...Won't try any write tests unless all read tests succeed."
      exit $failures
    else
      havewritten=1
    fi
  fi
  
  "$D"/$testnum >"$D"/$testnum.test 2>"$D"/$testnum.errs
  e=$?

  if [ $e -eq 0 ]
  then
    if cmp "$D"/$testnum.test "$D"/$testnum.ok >/dev/null 2>&1
    then
      successes="`expr $successes + 1`"
      echo "OK"
    else
      failures="`expr $failures + 1`"
      echo "FAILED!  Output different than expected.  Check $D/$testnum.test and $D/$testnum.errs for errors."
    fi
  elif [ $e -eq 111 ]
  then
    echo "SKIPPED"
  else
    failures="`expr $failures + 1`"
    echo "FAILED!  Exited with error code $e.  Check $D/$testnum.test and $D/$testnum.errs for errors."
  fi
done

echo "Passed" $successes "/" `expr $successes + $failures`
exit $failures
