#!/bin/sh
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
set -u  # force better programming and ability to use check for not set

if [ -z "${1-}" ] ; then echo usage $0 pid-file [process name]; exit 1; fi

if [ ! -r $1 ] ; then exit; fi

if [ "`basename $1`" != "mtpid" -a "`basename $1`" != "lost_pids" ]; then
  echo Stopping `basename $1 | sed -e 's/_pids$//'`
fi

cat $1 | while read pid; do
    if [ `echo "$pid" | egrep -c "[^0-9]"` -ne 0 ]; then
       if [ "$pid" != "-1" ]; then echo "bad pid \"$pid\" in pid file $1"; fi
    elif [ `ps -p $pid 2>&1 | grep -c $pid` -ne 0 ]; then 
      #ps -p $pid
      #echo "kill -9 $pid"
      kill -9 $pid
      cnt=0
      max=3
      while [ $cnt -le $max ]; do
        if [ `ps -p $pid 2>&1 | grep -c $pid` -eq 0 ]; then 
	  break
	elif [ $cnt -eq $max ]; then
          echo "ERROR: Process $pid STILL LIVES" 
	  break
        fi
	sleep 1
	cnt=`expr $cnt + 1`
      done
    fi
done

rm -f $1

# some jobs don't seem to die. search for them
if [ -n "${2-}" ]; then
  pid="`EPS returnpid $2`"
  if [ "$pid" != ""  -a "$pid" != "-1" ]; then 
    echo scan for lost job finds $2 ...trying to kill $pid again
    tmpfile=$ENSTORE_TMP/lost_pids
    rm -f $tmpfile
    echo "$pid">$tmpfile
    $0 $tmpfile "" # make sure 2nd argument is null to prevent loop
  fi
fi
