#!/bin/zsh

# to make the script fail safely
set -euo pipefail


out=${1:-output}

echo -e "" > $out

echo `date` | tee -a $out
echo "" >> $out
echo "Below is the feedback and provisional marks for your CW 3 submission." >> $out
echo "Please note all marks are provisional until ratified by the" >> $out
echo "assessment board -- this is not an official results transcript." >> $out
echo "" >> $out

echo "The feedback for your submission for cw03.sc" >> $out
echo "" >> $out

# marks for CW 3
marks=$(( 0.0 ))

# compilation tests

function scala_compile {
  (ulimit -t 30; JAVA_OPTS="-Xmx1g" amm -s "$1" 2> c$out 1> c$out)
}

# functional tests

function scala_assert {
  rm -rf /Users/cu/.ammonite/cache/3.*/* 2> /dev/null ;    
  (ulimit -t 30; JAVA_OPTS="-Xmx1g -XX:MaxJavaStackTraceDepth=10" amm -s "$1" 1>> $out 2>> $out)
}

function scala_fail {
  (ulimit -t 30; JAVA_OPTS="-Xmx1g -XX:MaxJavaStackTraceDepth=10" amm -s "$1" 1>> $out 2>> $out)
}



### compilation test

echo -e "0) cw03.sc compiles?\n" | tee -a $out

if (scala_compile "c.sc")
then
    echo -e "    --> yes cw03.sc compiles\n" | tee -a $out
    tsts=$(( 0 ))
else
    echo -e "    --> AMM DID NOT compile cw03.sc\n" | tee -a $out
    cat c$out | tee -a $out
    echo -e "\n\n" >> $out
    tsts=$(( 1 ))
fi

### parsing test
echo >> $out
#echo -e "\n\n\n" >> $out

if [ $tsts -eq 0 ]
then
  echo -e "1) Parsing test with example files (does it raise an exception):\n" | tee -a $out
  cat cw03.sc c3_add.sc > cw033_add.sc  
  if (scala_assert "c3.sc")
  then
      echo -e "   --> success (+ 6.0 Marks)\n" | tee -a $out
      marks=$(( marks + 6.0 ))
  else
      echo -e "   --> FAILED\n" | tee -a $out
      #cat $out | tee -a $out
  fi
fi

### eval test
echo >> $out
#echo -e "\n\n\n" >> $out

if [ $tsts -eq 0 ]
then
  echo -e "2) Evaluation of primes.while:\n" | tee -a $out
  cat c4_pre.sc cw03.sc c4_add.sc > cw034_add.sc  
  if (scala_assert "c4.sc")
  then
      echo -e "   --> success (+ 2.0 Marks)\n" | tee -a $out
      marks=$(( marks + 2.0 ))
  else
      echo -e "   --> FAILED\n" | tee -a $out
      #cat $out | tee -a $out
  fi
fi

### print test
echo >> $out
#echo -e "\n\n\n" >> $out

if [ $tsts -eq 0 ]
then
    echo -e "3) Testing of what is printed with the program:\n" | tee -a $out
    echo -e "\"\"\"" >> $out
    cat "test.while" >> $out
    echo -e "\"\"\"\n" >> $out
    if (scala_assert "c5.sc")
    then
	echo -e "   --> success (+ 2.0 Marks)\n" | tee -a $out
	marks=$(( marks + 2.0 ))
    else
	echo -e "   --> FAILED\n" | tee -a $out
	tail -25 $out | pr -to10
    fi
fi


## final marks
echo >> $out
echo "Overall mark for CW 3" | tee -a $out
printf " %0.2f\n" $marks | tee -a $out



