#! /bin/bash
timelimit=60
# Best effort to get the configured coredumpTimeout for
# an EOS Agent from its agent config file.
# Default to a timelimit of 60 seconds if the configured
# value could not be found.
agentName=$(grep ^$1$ -rl /var/run/agents/ | cut -d'.' -f2)

# In case of forked children of EOS Agents, do a best effort
# to get to the forked child's ancestor EOS Agent and get the
# EOS Agent's actual agentName. 
# Note: We cannot just assume procName==agentName, since the 
# agents like slice agents would have a different procName and
# agentName since the agentName includes the slice name as well.
# OTOH, we can't assume that agentName starts with procName due
# to special cases like ArBgp (procName=Bgp-main, agentName=Bgp).
if [ -z "$agentName" ]; then
   procName=$(ps -p $1 -o comm --no-headers)
   if [ ! -z "$procName" ]; then
      # 1. Run through all the agents whose names start with the same prefix as the procName
      #    (With "-" delimiter, see Bgp-main comment above).
      # 2. Get the PIDs of these agents( first line of their
      #    /var/run/agents/ file )
      # 3. Search for the current PID for which core is being dumped
      #    in the process tree of the agent PID.
      # 4. If found, use the agentName corresponding to the agent PID
      #    and get the timelimit value from its agentConfigFile.
      for agentPid in $(head -1 /var/run/agents/ar.${procName%%-*}* -q 2>/dev/null)
      do
         if [ ! -z $(pstree -p $agentPid | grep "($1)") ]; then
            agentName=$(grep ^$agentPid$ -rl /var/run/agents/ | cut -d'.' -f2)
            break 
         fi
      done
   fi
fi
   
if [ ! -z "$agentName" ]; then
   # We do not expect to see more than one agent config file
   # with the same agent name. But still get only the first
   # matching file to be on the safer side.
   agentConfigFile=$(grep "^\[$agentName\]$" -rl /etc/ProcMgr.d/run | head -n1)
   if [ ! -z "$agentConfigFile" ]; then
      timelimit=$(sed -n 's/coredumpTimeout = \(.*\)$/\1/p' $agentConfigFile)
      if [ -z "$timelimit" ]; then
         timelimit=60
      fi
   fi
fi

# For testing
if [ "$3" == "b160310partial" ]; then
   timelimit=0.000001
fi
# compress stdin and add core file annotation
/usr/bin/timeout $timelimit /bin/bash -c '( /usr/bin/cat -; /usr/sbin/core_annotate_util annotate ) | /usr/bin/pigz ' > /var/core/core.$1.$2.$3.partial.gz
if [ $? -eq 0 ]; then
   mv /var/core/core.$1.$2.$3.partial.gz /var/core/core.$1.$2.$3.gz
fi
# Increasing the gzip compression speed does not bring in significant
# difference for process restart and we also get larger output file.
# At this point we can also limit the number of per process cores stored
# We can do things like keeping the most recent per process core-files only
