#!/bin/bash

JAVA="java"
JAVAFLAGS=""
ANT="ant"

MAIN="ads1ws08.pa1.Main"
VIEWER="ads1ws08.pa1.viewer.ViewerApplication"
VIEWERTMP="viewertmp"
MAINJAR="ads1ws08.jar"

function compile
{
  $ANT jar
}

function run
{
  $JAVA $JAVAFLAGS -cp $MAINJAR $MAIN $*
}

function view
{
  run $* | tee $VIEWERTMP && \
  $JAVA $JAVAFLAGS -cp $MAINJAR $VIEWER $VIEWERTMP && \
  rm -f $VIEWERTMP
}

function do_test
{
  input="$1"
  output="$2"

  if [ ! -f "$input" ]
  then
    return
  fi
  if [ ! -f "$output" ]
  then
    echo "ERROR: outputfile for $input doesn't exist"
    exit 1
  fi

  echo "Testing $input ..."
  md5_1=$(run "$input" | md5sum)
  md5_2=$(md5sum < "$output")
  if [ "$md5_1" = "$md5_2" ]
  then
    echo "  SUCCESS"
  else
    echo " ERROR: output file differ..."
    exit 1
  fi
}

cmd="$1"
shift
case "$cmd" in
  c|compile|make)
    compile
  ;;
  r|run)
    compile >&2 && \
    run $*
  ;;
  test)
    file="$1"
    if [ ! -f "$file" ]
    then
      echo "ERROR: testfile doesn't exist"
      exit 1
    fi
    input="$file"
    output=$(dirname "$input")"/../output/"$(basename "$file")
    do_test "$input" "$output"
  ;;
  t|tests)
    for dir in $(find ./tests -type d -iname "input")
    do
      for file in $(ls $dir | sort)
      do
        input="$dir/$file"
        output="$dir/../output/$file"
        if [ ! -f "$input" ]
        then
          continue
        fi
        do_test "$input" "$output"
      done
    done
  ;;
  v|view)
    compile && \
    view $*
  ;;
esac
