#!/bin/csh -f

### SCRIPT_NAME: what name is this script truly called.
set SCRIPT_NAME = "dump_ppids"

if ( X`basename $0` != X$SCRIPT_NAME ) then
    # If invoked under any name other than the real one, it will
    # dump the stack to syslog instead of the screen, and will end
    # by calling <invoked_name>.real to run the real version.  That
    # allows you to do
    #     mv /usr/bin/foo /usr/bin/foo.real
    #     ln -s /usr/bin/isi_hwtools/dump_ppids /usr/bin/foo
    # and get both a syslog trace and standard output
    set RUNREAL = 1
    set LOGDEST = " | logger"
else
    set RUNREAL = 0
    set LOGDEST = ""
endif

if ($# == 0 || $RUNREAL == 1) then
    # if no args, or passing through to <invoked_name>.real, use current pid
    set PID = "$$"
else if ($# == 1) then
    # else use sole arg as pid
    set PID = "$1"
else
    # else usage: RUNREAL is known to be zero, so only show usage for that
    echo 'usage: $0 [pid]'
    exit 1
endif

## collect the parent PIDs
set PROCSCOMMA = "$PID"
set PROCSSPACE = "$PID"
set FINDPID = $PID
while ( 1 )
    set FINDPID = `( ps -o ppid= -p $FINDPID && exit 1 | tail +2 )`
    if ( $? != 0 || "x$FINDPID" == "x0" ) then
	# if we error or found the top, exit.
	break;
    endif
    set PROCSCOMMA = "$FINDPID,$PROCSCOMMA"
    set PROCSSPACE = "$FINDPID $PROCSSPACE"
end

## only works in bsd5
#echo "PID order is $PROCSCOMMA"
#ps -axwww -p$PROCSCOMMA
## this one also works in bsd4, also forces the right order, but sometimes
## messes up column alignment with certain ps options
eval "echo Run of \'$0 $*\' through PIDs...  $LOGDEST"
foreach PID ( $PROCSSPACE )
	eval "ps -axwww -p$PID | tail +2  $LOGDEST"
end

if ( $RUNREAL == 1 ) then
	$0.real $*
endif
