#!/bin/sh

set -u

res=0
status_file_path="/usr/share/smw/tests/"
def_file_ext=".json"
status_file_ext=".txt"

if [ $# -lt 1 ]
then
  echo "This script needs at least one Test definition file"
  exit 1
fi

#
# Check if the ELE Daemon is present
# If not active, exit with an error
#
if [ -e /etc/systemd/system/nvm_daemon.service ]; then
  res=$(systemctl is-active nvm_daemon)
  if [ "${res}" != "active" ]; then
    echo "NVM Daemon is not active"
    exit 1
  fi
fi

tmp_database_file=
final_status_file=
if [ $# -gt 1 ]; then
  final_status_file=$(basename "$1")
  final_status_file="${final_status_file%%.*}"
  tmp_database_file="${final_status_file}"
  final_status_file="${status_file_path}${final_status_file}${status_file_ext}"
  touch "${final_status_file}"

  find "/var/tmp/" -maxdepth 1 -type f -name "*${tmp_database_file}.dat" -exec rm {} \;
fi

for def in "$@"
do
  if [ -z ${VALGRIND+x} ]; then
    smwtest -d "${def}"
  else
    valgrind --undef-value-errors=no --error-exitcode=2 --suppressions=./scripts/leaks.supp smwtest -d "${def}"
  fi
  res=$?

  if [ -n "${final_status_file}" ]; then
    status_file=$(basename "${def}" "${def_file_ext}")
    status_file="${status_file_path}${status_file}${status_file_ext}"
    cat "${status_file}" >> "${final_status_file}"
    rm "${status_file}"
  fi

  if [ "${res}" -gt 1 ]; then
    echo "${def} test failed (${res})"
    break
  fi

  shift
done

exit ${res}
