#!/bin/sh

set -e

GONTC=${GONTC:-../gontc}

fail () {
  echo
  echo >&2 "$*"
  exit 1
}

echo -n "Testing "

for f in *.g ; do
  iface=$(basename $f .g).gi
  if test ! -f $iface ; then
    echo "/* Empty interface for $f */" > $iface
    $GONTC -c $iface
    rm $iface
  else
    $GONTC -c $iface
  fi
  if grep -q 'expected-build-status: fail' $f ; then
    if $GONTC -S $f > /dev/null 2> /dev/null ; then
      fail "unxpected success: $f"
    fi
  elif grep -q 'expected-build-status: ok' $f ; then
    if $GONTC -c $f ; then
      if grep -q 'run-test: yes' $f ; then
        if $GONTC $f -o test-result ; then
	  if ./test-result > test.output 2>&1 ; then
	    grep 'expected-output: ' $f | sed -e 's/.*: //' > expected.output
	    if cmp expected.output test.output ; then
	      rm -f expected.output test.output test-result
	    else
	      echo
	      echo "Expected output:"
	      echo "#v+"
	      cat expected.output
	      echo "#v-"
	      echo
	      echo "Got:"
	      echo "#v+"
	      cat test.output
	      echo "#v-"
	      fail "$f produced bad output"
	    fi
	  else
	    fail "$f failed to run"
	  fi
	else
	  fail "$f failed to link"
	fi
      elif grep -q 'run-test: no' $f ; then
        : # we're done
      else
        fail "$f does not contain run-test: tag"
      fi
    else
      fail "unxpected failure: $f"
    fi
  else
    fail "$f does not contain expected-build-status: tag"
  fi
  
  rm -f *.gio *.ksi
  echo -n "."
done

rm -f *.gio *.o *.ksi *.output

echo " done"
