#!/bin/sh
# Compile and execute the test cases in the current working directory

cleanup()
{
  rm -f *.s *.o core tempfile x.c a.out *.c.* err
}

if [ "x$1" = x-clean ]
  then
    cleanup
    chmod 0444 *.c
    exit 0
  fi

if [ $# = 0 ]
  then exec $0 gcc
  fi

if [ $# -gt 1 ]
  then
    for i in "$@"
      do ./$0 "$i"
      done
    exit 0
  fi

if [ -d "$1" ]
  then GCC="$1/xgcc -B$1/"
  else GCC="$1"
  fi
echo "TESTING WITH $GCC"

echo "main(){exit(0);}" > x.c
NATIVE=false
if $GCC x.c 2> /dev/null
  then if ./a.out; then NATIVE=true; fi
  fi
rm -f x.c

if $NATIVE
  then true
  else
    echo "Can't run these tests with that compiler"
    exit 0
  fi

FAILURES=0

testit()
{
  prog=$1
  shift
  $GCC $prog $@ -w -o /tmp/ctort.$$ 2> err
  status=$?
  if [ $status != 0 ]
    then
      if grep "fatal signal" < err > tempfile
        then
          signal=`sed 's;.*signal \(.*\)$;\1;' < tempfile`
          echo "ERROR: compiler got signal $signal with: $@"
          FAILURES=`expr $FAILURES + 1`
        else
          echo "ERROR: compiler returns exit status $status with: $@"
          FAILURES=`expr $FAILURES + 1`
        fi
    else	# Compilation OK.  Try to run the result.
      ./watchdog "[c]tort.$$" &
      sh -c /tmp/ctort.$$ 2> /dev/null
      status=$?
      kill $! 2> /dev/null
      if [ $status != 0 ]
        then
          if [ $status -ge 128 ]
            then
	      status=`expr $status - 128`
	      if [ $status = 15 ]
		then
		  echo "ERROR: compiled program seems to loop with: $@"
		else
		  echo "ERROR: compiled program got signal $status with: $@"
		  FAILURES=`expr $FAILURES + 1`
		fi
            else
              echo "ERROR: compiled program returns exit status $status with: $@"
              FAILURES=`expr $FAILURES + 1`
            fi
        fi
    fi
}

for i in `ls -r *.c`; do
  echo $i
  testit $i
  testit $i -O
  testit $i -O2
  testit $i -O2 -fomit-frame-pointer
  if egrep -s 'for|while' $i
    then
    testit $i -O2 -funroll-loops
    testit $i -O2 -funroll-all-loops
    fi
done

cleanup

if [ $FAILURES = 0 ]
  then echo "Test completed successfully."
else if [ $FAILURES = 1 ]
  then echo "Test completed with 1 failure."
else echo "Test completed with $FAILURES failures."
fi; fi
