#!/bin/ksh -p
#
# ident "@(#)bbkillproc.sh	1.3 02/06/06 SMI"
#
# Copyright 2000-2002 Sun Microsystems, Inc.  All rights reserved.
#
# $1 signal  
# $2 pid of the process to be killed
# $3 name of the executable
#
# return codes
#   0 signal was send to the process
#   1 failure
#   2 process didn't exist

Kill_All=0
echo "bbkillproc  $1 - $2 - $3 - $USER"

# do a recursive kill of this process and all its children
# $1 signal
# $2 parent pid
do_kill() {

	kids=`ps -e -o user,pid,ppid | nawk -v P=$2 '{ 
		if ( P == $3 ) 
			print $2
	}'`
	if [ "$kids" != "" ]; then
		for k in "$kids"; do
			( do_kill $1 $k )
		done
	fi
	print -n " $2"
}

usage() {
	echo "usage:"
        echo "$0 <signal> <pid> <exec name>"
	echo "$0 -r <signal> <pid>"
	echo "   -r kill all children of pid first before kill pid"
}

while getopts r c
do
    case $c in
        r)   	Kill_All=1;;
        \?)     usage
        	exit 1;;
    esac
done
shift `expr $OPTIND - 1`  

if [ $Kill_All != 0 ]; then
	if [ $# != 2 ];then
		usage
        	exit 1; 
	fi
else
	if [ $# != 3 ]; then 
		usage
                exit 1;
        fi       
fi

# does this process exist ?
kill -0 $2 > /dev/null 2>&1

if [ $? = 0 ]; then

    # yes, it does
    # find out if the process id is really what we are looking for
    cmd=`ps -u $USER -o pid,args | nawk -v P=$2 -v H=$3 '{

		if ( $1 == P || P == 0 )
			for (i=2; i<= NF; i++)
		     		if ( match($i,".*"H".*") ) {
					print $1;
					break;
				}
    	}'`	

    if [ ${#cmd} != 0 ]; then
	if [ $Kill_All != 0 ]; then
		pids=`do_kill $1 $cmd`
		kill -$1 $pids
	else
     		kill -$1 $cmd
		if [ $? != 0 -a $1 = 0 ]; then
			exit 2          # failure is interesting with kill -0
		fi
	fi
    else
	exit 2
    fi
else 
    exit 2
fi  

exit 0
