#!/bin/bash

nemu=build/nemu
[[ $show_log = 1 ]] && g_logfile=/tmp/nemu.test.log || g_logfile=/dev/null

echo "compiling NEMU..."
if make &> "$g_logfile"; then
  echo "NEMU compile OK"
else
  echo "NEMU compile error... exit..."
  cat "$g_logfile"
  exit 1
fi

echo "compiling testcases..."
if make -C $AM_HOME/tests/cputest ARCH=x86-nemu &> "$g_logfile"; then
  echo "testcases compile OK"
  cat "$g_logfile"
else
  echo "testcases compile error... exit..."
  cat "$g_logfile"
  exit 1
fi

[[ $show_log = 1 ]] && rm $g_logfile
files=`ls $AM_HOME/tests/cputest/build/*-x86-nemu.bin`
ori_log="build/nemu-log.txt"

has_fail=0

for file in $files; do
  base=`basename $file | sed -e 's/-x86-nemu.bin//'`
  printf "[%14s] " $base
  logfile=$base-log.txt
  $nemu -b -l $ori_log $file &> $logfile

  if (grep 'nemu: HIT GOOD TRAP' $logfile > /dev/null) then
    echo -e "\033[1;32mPASS!\033[0m"
  else
    echo -e "\033[1;31mFAIL!\033[0m see $logfile for more information"
    has_fail=1
    if (test -e $ori_log) then
      echo -e "\n\n===== the original log.txt =====\n" >> $logfile
      cat $ori_log >> $logfile
    fi
    head -n 512 $logfile >> $g_logfile
  fi
  rm -f $logfile
done

[[ $has_fail = 1 ]] && cat $g_logfile
exit $has_fail
