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

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

pending=
for arg
  do
    if [ x$pending = x ]
      then
	case $arg in
	-clean)
	  shift
	  cleanup
	  if [ $# = 0 ]
	    then exit 0
	    fi
	  ;;
	-options | -option | -opt)
	  shift
	  pending=opt
	  ;;
	# Add new option here
	*)
	  ;;
	esac
      else
	case $pending in
	  opt)
	    shift
	    opt_value="$arg"
	    ;;
	  # Add new option's argument handling here
	esac
	pending=
      fi
  done

if [ x$pending != x ]
  then
    echo "Usage: `basename $0` [-clean] [-options \"...\"] compiler-1 compiler-2 ..." 1>&2
    exit 2
  fi

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

sdir=`dirname $0`

if [ $# != 0 ]
  then compilers="$*"
  else compilers=gcc
  fi

for compiler in $compilers
  do

    if [ -d "$compiler" ]
      then GCC="$compiler/xgcc -B$compiler/ $opt_value"
      else GCC="$compiler $opt_value"
      fi

    NATIVE=false
    if $GCC $sdir/install-check.c 2> /dev/null
      then if ./a.out; then NATIVE=true; fi
      fi

    if $NATIVE; then true
      else
	echo "Can't run these tests with \"$GCC\""
	exit 1
      fi

    echo "TESTING WITH COMPILATION SEQUENCE:"
    $GCC $SC -v $sdir/install-check.c

    FAILURES=0

    for i in `cd $sdir; ls -r *.c`; do
      echo $i
      f=$sdir/$i
      testit $f
      testit $f -O
      testit $f -O2
      testit $f -O2 -fomit-frame-pointer
      if egrep >/dev/null 'for|while' $f
	then
	testit $f -O2 -funroll-loops
	testit $f -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

  done
