#!/bin/sh

TMPDIR=/tmp
BIRTHDAY=./birthday

RESULT=0
unset PASSED FAILED TAKEN KEEP

extract_section() {
  sed -ne "/^\\*$1/,/^\\*/p" "$2" | grep -v '^*'
}

runtest() {
  TFILE="$1"

  echo -n "$TFILE ... "

  ARGS=`extract_section args "$TFILE"`

  TMPROOT="$TMPDIR/bd.$$"
  extract_section file "$TFILE" > $TMPROOT.in

  $BIRTHDAY $ARGS -f $TMPROOT.in > $TMPROOT.out

  extract_section output "$TFILE" > $TMPROOT.exp

  if diff $TMPROOT.exp $TMPROOT.out; then
    echo ok
  else
    echo >&2 FAILED
    FAILED=A${FAILED}
  fi

  TAKEN=A${TAKEN}

  if test -z "$KEEP"; then
    rm $TMPROOT.in $TMPROOT.out $TMPROOT.exp
  else
    echo "Files saved as $TMPROOT.*"
  fi
}

while test "$#" != 0; do
  case "$1" in
    -exec) BIRTHDAY="$2"; shift ;;
    -keep) KEEP=yes ;;
    -*) echo >&2 "Bad arg $1"; exit 2 ;;
    *) runtest "$1" ;;
  esac
  shift
done

if test -z "$FAILED"; then
  echo `echo -n $TAKEN | wc -c` tests passed.
  exit 0
else
  echo `echo -n $FAILED | wc -c` of `echo -n $TAKEN | wc -c` tests FAILED.
  exit 1
fi
