#!/bin/bash
# RemoteBatchAppScript:makeSerialPackingTemplate
# SubmissionScripts/Distributor/Batch/APP/serialpacking
#
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
}

touch @@{JOBID}_@@{INSTANCEID}_output.tar.gz
rm -f @@{JOBID}_@@{INSTANCEID}_output.tar

workingDirectory=`pwd`
jobDirectory=`date "+%s"`_@@{JOBID}_@@{INSTANCEID}
mkdir ${jobDirectory}
cd ${jobDirectory}

export PATH=${workingDirectory}/${jobDirectory}:${PATH}

touch .__fileTimeMarker
sleep 1

tar xfz ${workingDirectory}/@@{JOBID}_@@{INSTANCEID}_input.tar.gz

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

@@{USEENVIRONMENT}
@@{ENVIRONMENT}

export RAPPTURE_GENERATED_FILE=.__rapptureGenerated_@@{JOBID}_@@{INSTANCEID}

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}

if [ -s ${RAPPTURE_GENERATED_FILE} ] ; then
   cat ${RAPPTURE_GENERATED_FILE} >> @@{TIME_RESULTS}
fi
rm -f ${RAPPTURE_GENERATED_FILE}

# Check for underlying Windows OS which makes all files executable
if [ -x @@{TS_FINISH} ] ; then
   changeMode=--mode="a-x,a+X"
fi

# Allow for file/directory names with embedded spaces.
find . -newer .__fileTimeMarker -not -name . -not -iname '*hub-proxy.*' -print0 | \
   xargs --null --no-run-if-empty tar rf ${workingDirectory}/@@{JOBID}_@@{INSTANCEID}_output.tar --no-recursion ${changeMode}
if [ -f ${workingDirectory}/@@{JOBID}_@@{INSTANCEID}_output.tar ] ; then
   gzip --force ${workingDirectory}/@@{JOBID}_@@{INSTANCEID}_output.tar
fi

cd ${workingDirectory}
rm -rf ${jobDirectory}
