#!/bin/bash

# to make the script fail safely
set -euo pipefail


out=${1:-output}

# read marks for CW6 part 1
marks=$(( `tail -1 $out` ))

echo $marks

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


# compilation tests

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

# 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|new Array' "$1" 2> /dev/null 1> /dev/null)
}


# var, .par return, ListBuffer test
#
echo "alcohol.scala does not contain vars, returns, Arrays, ListBuffers etc?" | tee -a $out

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

### compilation test


if  [ $tsts0 -eq 0 ]
then 
  echo "alcohol.scala runs?" | tee -a $out

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

### alcohol tests

if [ $tsts -eq 0 ]
then
  echo "get_csv tests:" | tee -a $out
  echo "  get_csv_page(url_alcohol).size == 194" | tee -a $out
  echo "  get_csv_file(file_population).size == 216" | tee -a $out

  if (scala_assert "alcohol.scala" "alcohol_test1.scala")
  then
      echo "  --> success" | tee -a $out
      marks=$(( marks + 1 ))
  else
    echo "  --> one of the tests failed" | tee -a $out
  fi
fi

### alcohol processing tests

if [ $tsts -eq 0 ]
then
  echo "processing tests:" | tee -a $out  
  echo "  process_alcs(alcs_list.drop(1))(0) == (\"Afghanistan\", 0.0)" | tee -a $out
  echo "  process_alcs(alcs_list.drop(1))(1) == (\"Albania\", 4.9)" | tee -a $out
  echo "  process_pops(pops_list.drop(1))(\"Micronesia\") == 104015" | tee -a $out
  echo "  process_pops(pops_list.drop(1))(\"Albania\") == 2889104" | tee -a $out
  
  if (scala_assert "alcohol.scala" "alcohol_test2.scala") 
  then
      echo "  --> success" | tee -a $out
      marks=$(( marks + 1 ))
  else
    echo "  --> one of the tests failed" | tee -a $out
  fi
fi

### alcohol percentage tests

if [ $tsts -eq 0 ]
then
  echo "calculation tests:" | tee -a $out  
  echo "  sorted_country_consumption().size == 177" | tee -a $out
  echo "  sorted_country_consumption()(9) == (\"United Kingdom\", 671976864)" | tee -a $out
  echo "  percentage(164) == (28771558364L, 28771558364L, 100.0)" | tee -a $out
  
  if (scala_assert "alcohol.scala" "alcohol_test3.scala") 
  then
      echo "  --> success" | tee -a $out
      marks=$(( marks + 1 ))
  else
    echo "  --> one of the tests failed" | tee -a $out
  fi
fi




## final marks
echo "Overall mark for Part 1 and 2" | tee -a $out
echo "$marks" | tee -a $out
