#!/usr/bin/env bash
############################################################################
# This shell processes pkill commands as required by the test scripts 
# on systems lacking the pkill commands (e.g. AIX). It does not 
# interpret all pkill options, only those required for these tests.
############################################################################
# Copyright (C) 2002 The Regents of the University of California.
# Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
# Written by Moe Jette <jette1@llnl.gov>
# UCRL-CODE-2002-040.
# 
# This file is part of SLURM, a resource management program.
# For details, see <http://www.llnl.gov/linux/slurm/>.
#  
# SLURM is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
# 
# SLURM is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
# 
# You should have received a copy of the GNU General Public License along
# with SLURM; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
#
# Read command line options
command=""
signal=""
user_id=-1
if [ $# -lt 4 ]; then
	echo "Usage: pkill -<signal> -u <user_id> <command>"
	exit 1
fi
if [ $1 == "-INT" ]; then
	signal="INT"
fi
if [ $1 == "-KILL" ]; then
	signal="KILL"
fi
if [ $1 == "-USR1" ]; then
	signal="USR1"
fi
if [ $1 == "-USR2" ]; then
	signal="USR2"
fi
if [ $2 == "-u" ]; then
	user_id=$3
fi
command=$4
# Validate command line options
if [ $command == "" ]; then
	echo "Need pattern/command"
	exit 1
fi
if [ $signal == "" ]; then
	echo "Need supported signal"
	exit 1
fi
if [ $user_id -eq -1 ]; then
	echo "Need user ID"
	exit 1
fi
# Find the appropriate processes and signal them
if [ $signal == "INT" ]; then
        ps -o "%p %c" -U $user_id | grep " $command" | awk '{printf "kill -s INT %s\n",$1}' | bash
	exit 0
fi
if [ $signal == "KILL" ]; then
        ps -o "%p %c" -U $user_id | grep " $command" | awk '{printf "kill -s KILL %s\n",$1}' | bash
	exit 0
fi
if [ $signal == "USR1" ]; then
	ps -o "%p %c" -U $user_id | grep " $command" | awk '{printf "kill -s USR1 %s\n",$1}' | bash
	exit 0
fi
if [ $signal == "USR2" ]; then
	ps -o "%p %c" -U $user_id | grep " $command" | awk '{printf "kill -s USR2 %s\n",$1}' | bash
	exit 0
fi
echo "Unsupported signal $signal"
exit 1
