#!/bin/bash
################################################################################
# This script tests if MATLAB license will expire soon on Windows.
#
# NOTE:
# - Assumes constant MATLAB_PATH is defined and points to MATLAB executable or 
#	application.
################################################################################

# Convert MATLAB_PATH to Windows format
MATLAB_PATH=$(cygpath -u $(cygpath -ms "${MATLAB_PATH}"))

# Check if MATLAB exists
if ! [ -d ${MATLAB_PATH} ]; then
	echo "${MATLAB_PATH} does not point to a MATLAB installation! Please modify MATLAB_PATH variable in Jenkins job and try again."
	exit 1
fi

# Start MATLAB, redirecting output to logfile and suppressing output to console
${MATLAB_PATH}/bin/matlab -nodesktop -nosplash -nojvm -r "exit;" -logfile matlab.log &

# Wait for MATLAB to exit
#
# TODO:
# - Replace by adding -wait option to above calls to matlab?
#
sleep 5;
echo "Waiting for MATLAB to exit"
pid=$(ps -W | grep MATLAB | awk '{print $1}')

# Time out after $max_time seconds because sometimes multiple MATLAB processes get locked in race condition
timer=0
max_time=7200
while [[ $timer -lt $max_time && -n "${pid}" ]]; do
	pid=$(ps -W | grep MATLAB | awk '{print $1}')
	timer=$((timer + 1))
	sleep 1;
done

# Check if timer hit $max_time
if [ $timer -eq $max_time ]; then
	echo "Testing timed out at ${timer} seconds"
	# Kill MATLAB processes
	pid=$(ps -W | grep MATLAB | awk '{print $1}')
	echo "${pid}" | xargs /bin/kill -f
	exit 1
fi

# Filter out Windows characters
cat matlab.log | tr -cd '\11\12\40-\176' > matlab.log2 && mv matlab.log2 matlab.log

# Check log for license expiration message
matlabLicenseExpiring=`grep -c -E "Your license will expire in" matlab.log`

if [ ${matlabLicenseExpiring} -ne 0 ]; then
	cat matlab.log
	echo "Login to build node to update MATLAB license."
	exit 1;
fi
