#!/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="'id',[IdFromString('Dakota')],'exclude',[234,244,250,417,444,445]"  # Exclude any tests with transient solutions that require a restart
MATLAB_PATH="/usr/local/MATLAB/R2019b"
INSTALL_DIR=~/Downloads
PACKAGE_NAME="ISSM"

# Exclude any tests with transient solutions that require a restart
#
# NOTE:
# - All non-excluded tests were running until recent changes to QMU
# - 418 fails with "malloc(): invalid next size (unsorted)""
#
PYTHON_NROPTIONS="--include_name 'Dakota' --exclude 234 244 250 417 418 444 445"
TARBALL_NAME="issm-linux-with_dakota"
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

# Check that Python tests run
echo "Running Python tests"

export ISSM_DIR="${INSTALL_DIR}"
export PATH="${PATH}:${ISSM_DIR}/bin"
export PYTHONPATH="${ISSM_DIR}/scripts"
export PYTHONSTARTUP="${PYTHONPATH}/devpath.py"
export PYTHONUNBUFFERED=1 # We don't want Python to buffer output, otherwise issm.exe output is not captured

rm python.log 2> /dev/null
./runme.py ${PYTHON_NROPTIONS} &> python.log 2>&1

# Check that Python did not exit in error
pythonExitCode=`echo $?`
pythonExitedInError=`grep -E "runme.py: error" python.log | wc -l`

if [[ ${pythonExitCode} -ne 0 || ${pythonExitedInError} -ne 0 ]]; then
	echo "----------Python exited in error!----------"
	cat python.log
	echo "-----------End of python.log-----------"

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

	exit 1
fi

# Check that all Python tests passed
numPythonTestsFailed=`cat python.log | grep -c -e "FAILED|ERROR"`

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