#!/bin/sh
#
#  $Id$
#
# (C) 2003 by the Board of Trustees of the Leland Stanford, Jr., University
#                          All Rights Reserved
# Produced by Andrew Hanushevsky for Stanford University under contract
#            DE-AC03-76-SFO0515 with the Deprtment of Energy
#Syntax:   StopOLB

# The following snippet is from the StartOLB.cf file.
#
MYOS=`/bin/uname | /bin/awk '{print $1}'`
if [ "$MYOS" = "SunOS" ]; then
MYNAME=`/usr/ucb/whoami`
else
MYNAME=`/usr/bin/whoami`
fi
CONDCHK=0

##############################################################################
#                           s u b r o u t i n e s                            #
##############################################################################

Emsg () {
    /bin/echo StopOLB: $1
    exit 4
    }

Terminate() {
    olbpid=$1
    killpid=$2

    # Verify that we can kill this process
    #
      if [ $MYNAME != root ]; then
         set -- `/bin/ps -p $olbpid -o user`
         if [ $2 != $MYNAME ]; then
            Emsg "User $MYNAME can't kill process $olbpid started by $2."
         fi
      fi

    # Now kill the process
    #
      set -- `/bin/kill -9 $killpid 2>&1`
      if [ $? -ne 0 ]; then
         shift 2
         Emsg "Unable to kill process $olbpid; $*."
         fi
    }

Check(){
    olbpid=$1

    # Check if the process is indeed dead
    #
      FOO=`/bin/ps -p $olbpid`
      if [ $? -eq 0 ]; then
         sleep 1
         FOO=`/bin/ps -p $olbpid`
         if [ $? -eq 0 ]; then
         /bin/echo "pid $olbpid is still alive..."
         /bin/echo $FOO
         fi
      fi

    }

##############################################################################
#                          m a i n   p r o g r a m                           #
##############################################################################

# Pick up options
#
while test -n "$1"; do
     if test -n "'$1'" -a "'$1'" = "'-d'"; then
        set -x
   elif test -n "'$1'" -a "'$1'" = "'-c'"; then
        CONDCHK=1
   else
        /bin/echo StopOLB: Invalid option - $1.
     fi
   shift
   done

# find the process number assigned to the OLB
#
  set -- `ps -e -o pid -o comm | grep '.*olbd$' | awk '{print $1}'`

  if [ -z "$1" ]; then
     msg="Unable to find OLB process number"
     if [ $CONDCHK -ne 1 ]; then
        Emsg "$msg; is it running?"
     fi
     /bin/echo StopOLB: $msg\; continuing.
     exit 0
  fi

# Kill each process that we have found
#
  for olbpid do
      Terminate $olbpid $olbpid
      done

# Make Sure they are dead
#
  sleep 1
  for olbpid do
      Check $olbpid
      done

# find and kill the process numbers assigned to the performance monitor
#
  set --  ''
  set -- `ps -e -o pid -o args | grep 'XrdOlbMonPerf' | grep -v grep | awk '{print $1}'`

  if [ ! -z "$1" ]; then
     for olbpid do
         Terminate $olbpid -$olbpid
     done
  fi

  /bin/echo StopOLB: OLB stopped.
