#!/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}" > /dev/null
}
fi

topPID=$$

trap cleanup HUP INT QUIT ABRT TERM

cleanup()
{
   echo "Abnormal termination by signal"
   killedExecutable=0
   pids=$(ps=${topPID}; while [ "${ps}" ]; do echo ${ps}; ps=$(echo ${ps} | xargs -n1 pgrep -P); done | tail -n +2)
   for pid in $(echo ${pids} | tr ' ' '\n' | tac) ; do
      if [ $(ps --no-headers -o pid,command ${pid} | grep -c @@{EXECUTABLE}) -eq 1 ] ; then
         kill -TERM ${pid}
         if [ $? -eq 0 ] ; then
            killedExecutable=1
         fi
	 break
      fi
   done
   if [ ! -s @@{TS_FINISH} ] ; then
      date +"%s" > @@{TS_FINISH}
   fi
   if [ ${killedExecutable} -eq 0 ] ; then
      exit 1
   fi
}

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}" > /dev/null
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 &
   wait %1
else
   { time -p @@{MANAGERCOMMAND} @@{EXECUTABLE} @@{ARGUMENTS}  < @@{STDIN} \
                                                              > @@{RUNNAME}_@@{INSTANCEID}.stdout \
                                                             2> @@{RUNNAME}_@@{INSTANCEID}.stderr & } \
                 > @@{TIME_RESULTS} 2>&1
   wait %1
   echo "Command exited with status $?" >> @@{TIME_RESULTS}
fi
@@{POSTMANAGERCOMMANDS}

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