#! /bin/sh

if [ -z $NICE_TOP ]; then

  NICE_TOP=$PWD
  # PWD return different values on different systems:
  # Nice/regtest with bash on Linux, Nice/ under sh on Digital Unix
  if expr $NICE_TOP : '.*regtest$' >/dev/null; then
    NICE_TOP=`dirname $NICE_TOP`
  fi

fi

export NICE_TOP

JAVA=${JAVA-java}

printf()
{
  /usr/bin/printf "$@"
}

echo()
{
  /bin/echo "$@"
}

### Nice specific

compile()
{
  (cd ..; LC_CTYPE=en_US "$NICE_TOP"/bin/nicec \
    -e -r -a regtest/"$1" -d . \
    --classpath=".:${NICE_TOP}/classes" regtest."$1")
  return $?
}

execute()
{
  $JAVA -classpath "$1.jar":..:${CLASSPATH} regtest.$1.fun
}

### Regression test suite

compile_error()
{
  pkg_compile_error=`expr $pkg_compile_error + 1`
  
  printf "\n\n\n%s produced a compilation error\n" $1
  echo "Compiler output is:"
  echo
  echo "###############"
  cat $1/compile.out
  printf "###############\n\n"
}

newpkg()
{
  pkg_new=`expr $pkg_new + 1`

  printf "\n\n\n%s is a NEW package\n" $1
  echo "Program output is:"
  echo
  echo "###############"
  cat $1/current.out
  printf "###############\n\n"
  echo -n "Is that correct? (y/n) "
  read correct
  if [ "$correct" = "y" -o "$correct" = "yes" ]; then
    pkg_new_ok=`expr $pkg_new_ok + 1`
    mv $1/current.out $1/ok.out
  fi
}

exec_error()
{
  pkg_broken=`expr $pkg_broken + 1`
  printf "%s produced messages on stderr. It must be BROKEN.\n" $1
  echo
  echo "###############"
  cat $1/current.err
  printf "###############\n\n"
}

different_output()
{
  pkg_broken=`expr $pkg_broken + 1`
  echo "$1 is BROKEN"
}

regtest()
{
  execute $1 >$1/current.out 2>$1/current.err

  [ -s $1/current.err ] && { exec_error $1; return; }

  [ -r $1/ok.out ] || { newpkg $1; return; }
  cmp $1/ok.out $1/current.out || { different_output $1; return; }
  pkg_ok=`expr $pkg_ok + 1`
}

status()
{
  echo "$pkg packages, $pkg_ok OK, $pkg_compile_error compilation failures, $pkg_broken BROKEN, $pkg_new NEW ($pkg_new_ok accepted)"
}

pkg=0
pkg_compile_error=0
pkg_new=0
pkg_new_ok=0
pkg_ok=0
pkg_broken=0

for subdir in *; do
  [ -r "$subdir"/main.nice -o -r "$subdir"/Makefile ] || continue

  pkg=`expr $pkg + 1`

  echo -n "Testing package \"$subdir\""

  # execute package dependent script before compilation
  if [ -r $subdir/Makefile ]; then
    echo -n " (preparing...)"
    if 
      (cd $subdir
      if make > prepare.out 2>&1; then
        true
      else
        echo "(preparation FAILED)"
        cat prepare.out
        exit 1
      fi
      ); 
    then 
      true
    else
      echo "Skipping this package"
      continue
    fi
    
  fi
  echo

  if compile $subdir >$subdir/compile.out 2>&1; then

    regtest $subdir

  else

    compile_error $subdir
  
  fi

  status
done

[ $pkg = $pkg_ok ] && exit 0

# There was some error found
exit 1