#!/bin/bash

# to make the script fail safely
set -euo pipefail


out=${1:-output}

echo "" > $out

echo "Below is the feedback for your submission collatz.scala" >> $out
echo "" >> $out


# compilation tests

function scala_compile {
  (ulimit -t 30 -m 1024000 ; scala "$1" 2>> $out 1>> $out) 
}

# functional tests

function scala_assert {
  (ulimit -t 30 -m 1024000 ; scala -i "$1" "$2" -e "" 2> /dev/null 1> /dev/null)
}

# purity test

function scala_vars {
   (egrep '\bvar\b|\breturn\b|\.par|ListBuffer|mutable' "$1" 2> /dev/null 1> /dev/null)
}


# var, .par return, ListBuffer test
#
echo "collatz.scala does not contain vars, returns etc?" >> $out

if (scala_vars collatz.scala)
then
  echo "  --> fail" >> $out
  tsts0=$(( 1 ))
else
  echo "  --> success" >> $out
  tsts0=$(( 0 )) 
fi

### compilation test


if  [ $tsts0 -eq 0 ]
then 
  echo "collatz.scala runs?" >> $out

  if (scala_compile collatz.scala)
  then
    echo "  --> success" >> $out
    tsts=$(( 0 ))
  else
    echo "  --> scala did not run collatz.scala" >> $out
    tsts=$(( 1 )) 
  fi
else
  tsts=$(( 1 ))     
fi

### collatz tests

if [ $tsts -eq 0 ]
then
  echo "collatz.scala tests:" >> $out
  echo "  collatz(1) == 0,1 or 4" >> $out
  echo "  collatz(6) == 9" >> $out
  echo "  collatz(9) == 20" >> $out

  if (scala_assert "collatz.scala" "collatz_test1.scala")
  then
    echo "  --> success" >> $out
  else
    echo "  --> one of the tests failed" >> $out
  fi
fi

### collatz-max tests

if [ $tsts -eq 0 ]
then
  echo "  collatz_max(10) == (20, 9)" >> $out
  echo "  collatz_max(100) == (119, 97)" >> $out
  echo "  collatz_max(1000) == (179, 871)" >> $out
  echo "  collatz_max(10000) == (262, 6171)" >> $out
  echo "  collatz_max(100000) == (351, 77031)" >> $out
  echo "  collatz_max(1000000) == (525, 837799)" >> $out

  if (scala_assert "collatz.scala" "collatz_test2.scala") 
  then
    echo "  --> success" >> $out
  else
    echo "  --> one of the tests failed" >> $out
  fi
fi


