#!/bin/sh
#
# slay 1.2 - kill all processes belonging to the specified user(s).
# by Chris Ausbrooks <fish@bucket.ualr.edu> 
# based on kall (a script of unknown origin)
# Please mail me any suggestions or corrections.
# Donations welcome.
# Changes by Pawel Wiecek <coven@debian.org>

# Revision history:
# 0.99	First attempt.
# 1.0	Added Butthead.
# 1.1	Added retribution.
# 1.2	Added slayee notification.

USER=`whoami`
SIGNAL=`echo $1 | grep '^\-.*'`
ME=`basename $0`
COOL='0'

# this piece of nested ifs is added for Debian package only
if [ -f /etc/slay_mode ]
then
 if grep -q mean /etc/slay_mode
 then
  MODE='mean'
 fi
 if grep -q nice /etc/slay_mode
 then
  MODE='nice'
 fi
 if [ -z $SLAY_BUTTHEAD ]
 then
  if grep -q butthead /etc/slay_mode
  then
   SLAY_BUTTHEAD='on'
  fi
  if grep -q normal /etc/slay_mode
  then
   SLAY_BUTTHEAD='off'
  fi
 fi
else
 MODE='mean'
 if [ -z $SLAY_BUTTHEAD ]
 then
  SLAY_BUTTHEAD='off'
 fi
fi

# Command line handling.
if [ "$SIGNAL" != "" ]; then
	shift
else
	SIGNAL="-KILL"
fi

# Help for loosers.
if [ "$1" = "" -o "$1" = "--help" ]; then
	echo "usage: $ME [-signal] name [name...]"
	if [ "$SLAY_BUTTHEAD" = "on" ]; then
		echo "       Like, kills people and stuff."
		else echo "       Kills all processes belonging to any of the given names."
	fi
	exit -1 
fi

# Misuse trap.
if [ "$USER" != "$1" ]; then
	if [ "$USER" != "root" ]; then
		if [ "$MODE" = "mean" ]; then
			$0 -KILL $USER
			else if [ "$SLAY_BUTTHEAD" = "on" ]; then
	 			echo "${ME}: Cut it out."
				else echo "${ME}: Only root gets to do that."
			fi
		fi
		exit 2
	fi
fi

# Main body.
while [ "$1" != "" ]; do

# NOTE:  You may have to modify the next line, since PS is non-portable.
# The 'awk' command picks out the process IDs to pass them on to kill.
	rprocs=`ps caux | awk '{if(user == $1) print $2}' user=$1 -`
	if [ "$rprocs" != "" ]; then
		if [ "$1" = "$USER" ]; then
			if [ "$SLAY_BUTTHEAD" = "on" ]; then
				echo "${ME}: Beavis, don't make me have to smack you."
				else echo "${ME}: Illegal operation."
			fi
		fi
		COOL="1"
		if [ "$SLAY_BUTTHEAD" = "on" ]; then
			echo "${ME}: $SIGNAL is kicking $1's butt!"
			echo -e "\\fI'm kicking your butt.\\f" | write $1 2>/dev/null
			else echo "${ME}: Sending $SIGNAL signal to $1's process(es)..."
			echo -e "\\fYour current session has been terminated.\\f" | write $1 2>/dev/null
		fi
		kill $SIGNAL $rprocs 2>/dev/null
	fi
	shift
done

# Error message.
if [ $COOL = "0" ]; then
	if [ "$SLAY_BUTTHEAD" = "on" ]; then
		echo "${ME}: How old are you, Beavis?"
		else echo "${ME}: "Nothing done.
	fi
	exit 1
fi

# Non-error message.
if [ $COOL = "1" ]; then
	if [ "$SLAY_BUTTHEAD" = "on" ]; then
		echo "${ME}: Whoa, I have the power supreme."
		else echo "${ME}: Done."
	fi
	exit 0
fi
