#!/bin/bash

binary="./mycpu"
tmpfile="test/tmpfile"
inputs=( $(ls test/* | grep _program | sort -n) )

for input in ${inputs[@]}
do
  echo "Testing $input ..."

  programfile="$input"
  args="-c $programfile"
  memoryfile="${input/_program/_memory}"
  reffile="${input/_program/_output}"
  if [ -e "$memoryfile" ]
  then
    args+=" -m $memoryfile"
  fi

  if [ ! -e "$reffile" ]
  then
    echo "  ERROR: reference file $reffile doesn't exist"
    exit 1
  fi

  rm -rf "$tmpfile"
  echo "  Executing $binary $args ..."
  $binary $args > $tmpfile

  md5_1=$(md5sum < "$reffile")
  md5_2=$(md5sum < "$tmpfile")
  if [ "$md5_1" != "$md5_2" ]
  then
    echo "  ERROR: output and $reffile differ"
    diff -Naur "$reffile" "$tmpfile"
    rm -rf "$tmpfile"
    exit 1
  else
    echo "  SUCCESS"
  fi
  rm -rf "$tmpfile"
done
