#!/bin/bash
#This bash script calls the nightlyrun.m matlab file to run our nightly test decks. 
#It then processes the results and sends an email to the Ice developpers.

#Some functions 
function today_date {
suffix=`date | awk '{printf("%s-%s-%s",$2,$3,$6);}'` 
echo $suffix;
}

export ISSM_DIR="/home/seroussi/Ice/ice1/cron/ice1"

ICE_RELEASE="ice1";
ICE_REPOSITORY="/home/larour/Ice_Repository";

#Figure out today's date
today=`today_date`;
host_name=`hostname`;

#Erase code
rm -rf $ICE_RELEASE

#Fetch cvs code
cvs -d $ICE_REPOSITORY co -P $ICE_RELEASE

source $ISSM_DIR/etc/environment.sh

#Go to the ice directory
cd $ICE_RELEASE
ICEDIR=`pwd`;

#install ISSM
cd scripts
sh quickinstall.sh
cd ..

#Figure out mailing list
source cron/mailinglist

#Launch matlab and the nightly run script
matlab -nodisplay  > ./nightly.log << EOF 
startup
nightlyrun;
EOF

#Process log for errors 
cat nightly.log | grep ERROR > errors1.log
cat nightly.log | grep SUCCESS > errors2.log
cat errors1.log errors2.log > errors.log
		
#Mail
ERRORS=`cat errors.log`
if [ `expr length "$ERRORS"`  = "0" ]; then
	for i in `echo $MAILINGLIST`
		do
			mail -s "Nightly runs of $ICE_RELEASE on: $host_name. Date:$today. DID NOT WORK CORRECTLY" $i < nightly.log
		done
else
	for i in `echo $MAILINGLIST`
		do  
			mail -s "Nightly runs of $ICE_RELEASE on: $host_name. Date:$today." $i < errors.log
		done
fi

#Erase log and error logs
rm -rf nightly.log errors1.log errors2.log errors.log

#Erase ice code
cd ..
rm -rf $ICE_RELEASE

#back to old ISSM_DIR
ISSM_DIR=$OLDISSM_DIR
export ISSM_DIR
