#!/bin/bash
#
# Compare results of current test run and previous test run.
#
set -e
set -u
set -o pipefail


EXACT=""
FUZZY=""
MISSING=""

while getopts 'efm' OPTION; do
  case "$OPTION" in
    e)
      EXACT="-exact"
      ;;

    f)
      FUZZY="-fuzzy"
      ;;

    m)
      MISSING="-missing"
      ;;

    ?)
      echo "script usage: $(basename $0) [-m]" >&2
      exit 1
      ;;
  esac
done
shift "$(($OPTIND -1))"


# cd to location of script
cd "$(dirname "$0")"

if [ -z ${PHARMCAT_DATA_DIR+x} ]; then
  dataDir="../../../build"
else
  # expect PHARMCAT_DATA_DIR to be a relative directory
  dataDir="../../../${PHARMCAT_DATA_DIR}"
fi

oldFile="../../../src/test/autogenerated/autogenerated_test_report${EXACT}${FUZZY}${MISSING}.txt"

if [[ ! -f $oldFile ]]; then
  echo "Nothing to compare to."
  echo "Cannot find ${oldFile}"
  exit
fi
OLD=$(grep "# failed" "${oldFile}" || true)
if [[ ! -n $OLD ]]; then
  echo "No old data in ${oldFile}"
  exit
fi

newFile="${dataDir}/autogeneratedTestResults/autogenerated_test_report.txt"
if [[ ! -f $newFile ]]; then
  echo "Missing new data file: ${newFile}"
  exit
fi
NEW=$(grep "# failed" "${newFile}" || true)
if [[ ! -n $NEW ]]; then
  echo "No new data in ${newFile}"
  exit
fi

echo ""
echo ""
if [[ $OLD != "$NEW" ]]; then
  echo "***** TEST RESULTS MISMATCH! *****"
  echo "OLD: $OLD"
  echo "NEW: $NEW"
  echo "***** TEST RESULTS MISMATCH! *****"
else
  echo "=====> NO CHANGE TO RESULTS <====="
fi
echo ""
echo ""
rm $oldFile
grep -v Elapsed $newFile > $oldFile
