#!/bin/sh
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
# this is cheap argument processing. Must be in this order when checking. I want it cheap!
if [ "${1:-}" = "-c" ] ; then CHECK=1;                  shift; else CHECK=0;                   fi
if [ "${1:-}" = "-v" ] ; then SKIP="ecron|ekill|rgang"; shift; else SKIP="`/bin/echo '\001'`"; fi #skip grep|ekill or ^a 
if [ "${1:-}" = "-9" ] ; then SIG='-9';                 shift; else SIG=' ';                   fi

if [ -z "${1:-}" ]; then echo 'USUAGE: $0 [-c -9] \"egrep search string for kill\"'; exit 2; fi
lookfor="${1}"
l2=`echo $lookfor | sed -e 's/|/\\\|/g'`

UNAME="/bin/uname"
PS="/bin/ps"
ECHO="/bin/echo"
EGREP="/bin/egrep"
KILL="/bin/kill"
SLEEP="/bin/sleep"
SLEEPTIME=3

if [ `$UNAME` != "Linux" ]; then
    echo 'Sorry this only works for Linux.  You need to edit and fix $0'
    exit 1
fi

$PS axwww | $EGREP "$lookfor"| $EGREP -v "$SKIP" |while read pid line; do
   #echo $pid $line
# do not kill ourselves
    if [ ! "$pid" = "$$" -a `$ECHO $line | $EGREP -c "$EGREP $l2"` -eq 0 ]; then
      $ECHO killing $SIG $pid $line
      if [ $CHECK -eq 0 ]; then echo -n $KILL $SIG $pid; $KILL $SIG $pid;
          if [ $? -ne 0 ]; then echo ' FAILURE'; else echo ' OK'; fi
      fi
    else
      $ECHO "skipping $pid $line"
    fi
done;

if [ $CHECK -eq 0 ]; then
    if [ `$PS axwww | $EGREP "$lookfor"|$EGREP -v "$EGREP $l2" | wc -w` -eq 0 ]; then exit 0; fi

    $SLEEP $SLEEPTIME

    x="`$PS axwww | $EGREP "$lookfor"|$EGREP -v 'grep|ekill'`"
    if [ `echo "$x" | wc -w` -eq 0 ]; then exit 0; fi
    $ECHO
    $ECHO "These survived after the kill:"
    $ECHO "$x"
    exit 1
fi
exit 0
