#!/bin/bash
###############################################################################
## tracedump                                                                   #
###############################################################################
## Copyright 2002. Spinnaker Networks Inc.                                    #
## All rights reserved.                                                       #
##                                                                            #
###############################################################################
## This script is generates the stack dump of all the threads of the          #
## spinmgmt application (Tomcat process)                                      #
##                                                                            #
###############################################################################

BASEDIR=`dirname $0`

#########
## Function: Usage
## Displays the Usage for this script
#########
Usage ()
{
    echo "usage:  tracedump [-t <target executible>] [-d <debugger>] [-h]"
    echo "            t:  (optional) The path to the target executible"
    echo "                if not specified, defaults to the Tomcat installation"
    echo "            d:  (optional) The path to the gdb debugger"
    echo "                if not specified, defaults to the installed gdb"
    echo "            h:  displays this usage message"
}

#########
## Retrieve the Command Line Options
#########
GETOPTS="getopts ':t:d:h' OPTION $*"

${GETOPTS}
RET=$?
while [ ${RET}  -le 0 ]
do
  case ${OPTION} in
      t)  TARGET_EXE=${OPTARG}
	  BASEDIR=`dirname ${TARGET_EXE}`
	  ;;
      d)  GDB_EXE=${OPTARG}
	  ;;
      *)  Usage
	  exit 1
	  ;;
  esac

  ${GETOPTS}
  RET=$?
done

#########
## Initialize the defaults
#########
if [ -z ${GDB_EXE} ]; then
    GDB_EXE=/usr/spinmgmt/bin/gdb5.2.1 
    if [ ! -f  ${GDB_EXE} ]; then
	GDB_EXE=/usr/bin/gdb
    fi
fi

if [ ! -f  ${BASEDIR}/../lib/functions ]; then
   BASEDIR="/usr/spinmgmt/bin";
fi

. ${BASEDIR}/../lib/functions;

if [ -z ${TARGET_EXE} ]; then
    TARGET_EXE="${HOMEDIR}/bin/Tomcat"
fi

#########
## Generate the stack trace
#########
PID=`getParentPid "${TARGET_EXE}"`;
RETVAL=$?
if [ $RETVAL -eq 0 -a -n "$PID" ]; then

   echo "handle SIGPWR nostop noprint" > /tmp/tracedump.gdb
   echo "handle SIGXCPU nostop noprint"  >> /tmp/tracedump.gdb
   echo "set height 0"  >> /tmp/tracedump.gdb
   echo "target exec ${TARGET_EXE}" >> /tmp/tracedump.gdb
   echo "attach ${PID}"  >> /tmp/tracedump.gdb
   echo "thread apply all bt"  >> /tmp/tracedump.gdb
   echo "quit"  >> /tmp/tracedump.gdb
   echo ""  >> /tmp/tracedump.gdb

   ${GDB_EXE} < /tmp/tracedump.gdb 

   rm -f /tmp/tracedump.gdb
else
   echo "Error: ${TARGET_EXE} is not running" >&2
fi