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

# bin/$RCSfile$  $Revision$
# a file to do a ps on different OS's and check for Enstore-like programs

if [ $# = 0 ];
then
   p=" "
   returnpid=0
else
   if [ "$1" != "returnpid" ]; then
     p="$@"
     returnpid=0
   else
     p=" "
     returnpid=1
     lookfor=${2-:enstore}
   fi
fi
case `uname` in
  Linux*)
	# check if tread display is implemented
	ps m > /dev/null 2>&1
	if [ $? != 0 ]; then
	    x=`ps axuww  $p`
	else
	    #x=`ps axuwwm $p`
	    x=`ps -Leo uname,pid,%cpu,%mem,vsz,lwp,nlwp,tname,stat,start_time,cputime,args`
	fi
	;;
  OSF1*)
	x=`ps axguww $p`
	;;
  SunOS*)
	x=`ps -ef    $p`
	;;
  IRIX*)
	x=`ps -ef    $p`
	;;
  Darwin*)
	x=`ps -e -o ruser,pid,%cpu,%mem,vsz,tty,stat,start,time,command $p`
	;;
      *)
	x=`ps -ef $p`
	;;
esac

if [ $returnpid -eq 0 ]; then
  echo "$x" | sort | egrep -v '\[?EPS\]?|ngop|\[?grep\]?| \[?sort\]?| \[?ps\]?| \[?\-?bash\]?| \[?tail\]?| \[?xnetload\]?| \[?tee\]?| \[?r?s?login\]?| \[?su\]?| \[?emacs\]?|\[?cumin\]?' | egrep 'python| enstore|encp|configuration_server|log_server|alarm_server|ratekeeper|event_relay|inquisitor|info_server|file_clerk|volume_clerk|accounting_server|drivestat_server|library_manager|media_changer|mover|monitor_server|pnfs_agent|reader|writer|dasadmin|mt |db_|dbserver|pmountd|pnfsd|zombie|selread|sdrread|ipmisrv|dogread|dogarm|dogdisarm|deadman|run_misc_command|httpd|conserver|chip2|getcons|enrsh|enrcp|nanny|rsh|rcp|fixme|rsync|ecron|postmaster|qpidd'
else
  echoed=0
  oldIFS="$IFS"
  IFS="
"
  newIFS="$IFS"
  for psl in $x; do
    IFS="$oldIFS"
    #echo "psline $psl x${lookfor}x"
    psline=`echo "$psl" | grep $lookfor | egrep -v 'grep|ngop|returnpid|pidkill' | grep \`whoami\``
    # is the pid always the 2nd field???????
    pid=`echo $psline | cut -f2 -d' '` # no quotes arounds $psline removes spaces
    if [ "$pid" != "" ]; then
      echo $pid
      echoed=1
    fi
    IFS="$newIFS"
  done
  IFS="$oldIFS"
  if [ $echoed -eq 0 ]; then echo -1; fi
fi
