#!/bin/bash

# This script is intended to test binaries downloaded to a user-end machine.
#
# NOTE: Tarball must already exist in INSTALL_DIR
#

MATLAB_NROPTIONS="'exclude',[IdFromString('Dakota'),125,126]" # Exclude Dakota tests and any tests with transient solutions that require a restart
MATLAB_PATH="/usr/local/MATLAB/R2019b"
INSTALL_DIR=~/Downloads
PACKAGE_NAME="ISSM"
TARBALL_NAME="issm-linux"
TARBALL="${TARBALL_NAME}.tar.gz"

cd ${INSTALL_DIR}
rm -rf ${PACKAGE_NAME}
tar -zxvf ${TARBALL}
cd ${PACKAGE_NAME}/test/NightlyRun

# Check that MATLAB tests run
echo "Running MATLAB tests"
rm matlab.log 2> /dev/null

# Run MATLAB tests redirecting output to logfile and suppressing output to console
${MATLAB_PATH}/bin/matlab -nojvm -nosplash -r "try, addpath ../../bin; addpath ../../lib; runme(${MATLAB_NROPTIONS}); exit; catch me,fprintf('%s',getReport(me)); exit; end" -logfile matlab.log &> /dev/null

# Check that MATLAB did not exit in error
matlabExitCode=`echo $?`
matlabExitedInError=`grep -E "Activation cannot proceed|license|Error" matlab.log | wc -l`

if [[ ${matlabExitCode} -ne 0 || ${matlabExitedInError} -ne 0 ]]; then
	echo "----------MATLAB exited in error!----------"
	cat matlab.log
	echo "-----------End of matlab.log-----------"

	# Clean up execution directory
	rm -rf ${ISSM_DIR}/execution/*

	exit 1
fi

# Check that all MATLAB tests passed
numMatlabTestsFailed=`cat matlab.log | grep -c -e "FAILED|ERROR"`

if [[ ${numMatlabTestsFailed} -ne 0 ]]; then
	echo "One or more MATLAB tests FAILED"
	exit 1;
else
	echo "All MATLAB tests PASSED"
fi
