#!/bin/sh
# 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}

TIMEPATH=
for timePath in /bin/time /usr/bin/time /usr/local/bin/time ; do
   if [ -x ${timePath} ] ; then
      TIMEPATH=${timePath}
      break
   fi
done

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

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

@@{PREMANAGERCOMMANDS}
${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
@@{POSTMANAGERCOMMANDS}

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