#!/bin/sh

set -e

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

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

try_run () {
  if grep -q 'run-test: yes' $f ; then
    if $GONTC $(echo $f | sed -e 's/\.g/.o/') -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
}

for f in *.g ; do
  echo "testing $f"
  iface=$(basename $f .g).gi
  if test ! -f $iface ; then
    echo "/* Autogenerated 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 2> /dev/null ; then
      fail "unxpected success: $f"
    fi
  elif grep -q 'expected-build-status: ok' $f ; then
    if $GONTC -c $f ; then
      try_run
    else
      fail "unxpected compilation failure: $f"
    fi
  elif grep -q 'expected-build-status: warn' $f ; then
    if $GONTC -Werror -S $f 2> /dev/null ; then
      fail "didn't get expected warning: $f"
    else
      if $GONTC -c $f 2> /dev/null ; then
        try_run
      else
        fail "got error instead of warning: $f"
      fi
    fi
  else
    fail "$f does not contain expected-build-status: tag"
  fi
  
  rm -f *.gio *.ksi
done

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