#!/bin/bash
#$ -S /bin/sh
#$ -cwd
#$ -l h_rt=@@{WALLTIME}
#$ -N JOB_@@{JOBID}_@@{INSTANCEID}
#$ -o sge_@@{RUNNAME}_@@{INSTANCEID}.stdout
#$ -e sge_@@{RUNNAME}_@@{INSTANCEID}.stderr
#$ -m n
@@{REMOTEBATCHACCOUNT}
@@{QUEUE}
@@{SUBMISSIONSCRIPTCOMMANDS}

@@{ENVIRONMENT}

# RemoteBatchSGE:makeSerialTemplate
# SubmissionScripts/Distributor/Batch/SGE/serial

trap cleanup HUP INT QUIT ABRT TERM

cleanup()
{
   echo "Abnormal termination by signal"
   if [ ! -s @@{TS_FINISH} ] ; then
      date +"%s" > @@{TS_FINISH}
   fi
   if [ ! -s @@{TIME_RESULTS} ] ; then
      cat > @@{TIME_RESULTS} << EOF
Command terminated by signal 3
real 0.00
user 0.00
sys 0.00
EOF
   fi
   exit 1
}

export PATH=${SGE_O_WORKDIR}:${PATH}
# Change to directory where job was submitted.
cd ${SGE_O_WORKDIR}

@@{QUOTA}

date +"%s" > @@{TS_START}

@@{PREMANAGERCOMMANDS}
TIMEPATH=
if [ -n "@@{TIMEPATHS}" ] ; then
   for timePath in @@{TIMEPATHS} ; do
      if [ -x ${timePath} ] ; then
         TIMEPATH=${timePath}
         break
      fi
   done
fi

if [ -n "${TIMEPATH}" ] ; then
   ${TIMEPATH} --format "Command exited with status %x\nreal %e\nuser %U\nsys %S" -o @@{TIME_RESULTS} \
      @@{MANAGERCOMMAND} @@{EXECUTABLE} @@{ARGUMENTS}  < @@{STDIN} \
                                                       > @@{RUNNAME}_@@{INSTANCEID}.stdout \
                                                      2> @@{RUNNAME}_@@{INSTANCEID}.stderr
else
   { time -p @@{MANAGERCOMMAND} @@{EXECUTABLE} @@{ARGUMENTS}  < @@{STDIN} \
                                                              > @@{RUNNAME}_@@{INSTANCEID}.stdout \
                                                             2> @@{RUNNAME}_@@{INSTANCEID}.stderr ; } \
                 > @@{TIME_RESULTS} 2>&1
   echo "Command exited with status $?" >> @@{TIME_RESULTS}
fi
@@{POSTMANAGERCOMMANDS}

date +"%s" > @@{TS_FINISH}
