#!/bin/bash
#
# Description: Kill the process group id contained in the first line, of the lines
#              returned by the "ps -Aww -o pid,pgid,args" command, that has 
#              the token in it.
#
# Change Activity:
#   10/19/2004 P. Callaghan - initial version
#   11/29/2007 L. Brocious  - Clean up, enhance FFDC
#
#STARTUSAGE
#
# Usage:
#   killGroupOf token
#
# Where:
#   token is the token/string to check for in the lines.
#
#ENDUSAGE
#****************************************************************************

# Function to return the process group ID of the PID running the specified program.
# Arguments
#  program
getpgid() {
   # Loop through "ps" output to find the PGID.
   ps -Aww -o pid,pgid,args | while read -r pid pgid cmd; do
      if [ "$cmd" == "$1" ]; then
         echo $pgid   # Return the PGID to our caller.
         break
      fi
   done
}

cmd="$1"
me=$(basename $0)

if [ $# -lt 1 ] ; then
   echo "$me: missing required argument"
   exit 1
fi

pgid=$(getpgid "$cmd")
if [ -z $pgid ]; then
   echo "$me: No process found running with cmd='$cmd'"
   exit 2
else
   #echo kill -9 -$pgid
   killcmd="kill -9 -$pgid"    # Command to kill all processes in the process group
   $killcmd
   killrc=$?
   if [ "$killrc" != "0" ] ; then
      echo "$me: '$killcmd' to kill process group with cmd='$cmd' failed with rc=$killrc"
   fi
   exit $killrc
fi
