#!/pkg/bin/ksh
#
# Collect debug information on the supplied pid before it is killed.
# If we have 10 or more snaps, delete all but the 5 oldest and 4 newest snaps.
#
# September, Hiroyuki Asano
# 
#  Copyright (c) 2007, 2010 by cisco Systems, Inc.
#  All rights reserved.
#

usage="[-C console_node] pid_of_caller calling_process calling_function line_number pid"
GETAPPMEDIA="/pkg/sbin/getappmedia"

unset CONSOLE_NODE
  while getopts C: c
  do
      case $c in
      C) CONSOLE_NODE=$OPTARG;;
      *) echo "Usage: $0 $usage" >&2; exit 1;;
      esac
  done

# Move forward in the argument list
shift $(($OPTIND - 1))

# We expect 5 arguments. 
if [ -z $5 ]
then
    echo "Usage: $0 $usage" >&2
    exit 1
fi

calling_pid=$1
shift
calling_process=$1
shift 
function=$1
shift
line=$1
shift
pid=$1
shift

[[ ! -x $GETAPPMEDIA ]] && {
	echo "Could not find $GETAPPMEDIA"
	return
}
echo "START SCRIPT" 
if [ -n "$CONSOLE_NODE" ]; then
DEV=`$GETAPPMEDIA -C $CONSOLE_NODE diag`
else
DEV=`$GETAPPMEDIA diag`
fi

[[ ! -d $DEV ]] && {
	echo "Destination directory not found ($DEV)"
	return
}

DEBUG_DIR=/tmp
if [[ $DEV != "/dev/shmem" && ! -d $DEBUG_DIR ]]
then
    echo "Making $DEBUG_DIR" 2>&1 
    mkdir $DEBUG_DIR
fi

DEBUG_FILE="$DEBUG_DIR/ssm_restart_$pid.log"

# Define an array of debug files, sorted in time increasing order
set -A debug_files `ls -tr $DEBUG_DIR/ssm_restart_* 2>/dev/null`

# 'i' is the index of the last array element
i=${#debug_files[*]} 
# If 10 or more files in the directory...
if [ $i -ge 4 ]
then
    # Keep the 5 oldest and 4 newest
    k=$(($i-4))
    j=5
    while [ $j -lt $k ]
    do
        rm ${debug_files[$j]} 2>/dev/null
	j=$(($j+1))
    done
fi

echo "$0 invoked by pid $calling_pid ($calling_process) for pid $pid.
Output is in $DEBUG_FILE" > /dev/syslog/LOG_DEBUG/ssm

# Generate the snap
(
echo "----------------------------------------------------------------"
echo "Gathering attach_process output for process. Time `iosclock -d 0x0`"
echo "----------------------------------------------------------------"
echo "Output from attach_process -A -p $pid -i 1"
attach_process -A -p $pid -i 1
echo "Output from show process blocked"
show_processes -b
echo "----------------------------------------------------------------"
echo "Exiting at  at `iosclock -d 0x0`."

) > $DEBUG_FILE 2>&1
