#!/bin/ksh
#
# ident "@(#)bbkillproc.sh 1.2     01/04/09 SMI"
#
# Copyright (c) 2000 by 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 -e -o user,pid,args | nawk -v U=$USER -v P=$2 -v H=$3 '{

    		if ( $1 == U && ( $2 == P || P == 0 ) )
		    	for (i=3; i<= NF; i++)
		     		if ( match($i,".*"H".*") ) {
            				printf("%s",P );
					break;
				}
    	}'`	

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

exit 0
