#!/bin/bash
# RemoteBatchAppScript:makeSerialTemplate
# SubmissionScripts/Distributor/Batch/APP/serial
#
jobId=$1
if [ $# -eq 1 ] ; then
# close stdin
   exec 0<&-
# close stdout and stderr
   exec 1<&-
   exec 2<&-

# open stdout
   exec 1> script_@@{RUNNAME}_@@{INSTANCEID}.stdout
# open stderr
   exec 2> script_@@{RUNNAME}_@@{INSTANCEID}.stderr

   trap callHome EXIT

   callHome()
{
   curl --silent --show-error \
        --request POST "https://@@{SUBMITHOSTFQDN}/api/v1/headnodeJobComplete/@@{INSTANCETOKEN}?${jobId}"
}
fi

trap cleanup HUP INT QUIT ABRT TERM

cleanup()
{
   echo "Abnormal termination by signal"
   if [ ! -s @@{TS_FINISH} ] ; then
      date +"%s" > @@{TS_FINISH}
   fi
   exit 1
}

CURDIR=`pwd`
export PATH=${CURDIR}:${PATH}

@@{USEENVIRONMENT}
@@{ENVIRONMENT}

if [ -n "${jobId}" ] ; then
   curl --silent --show-error \
        --request POST "https://@@{SUBMITHOSTFQDN}/api/v1/headnodeJobRunning/@@{INSTANCETOKEN}?${jobId}"
fi

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}
