#!/bin/sh
#
#  $Id: StopXRD,v 1.5 2004/12/15 02:55:30 abh Exp $
#
# (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:   StopXRD

# The following snippet is from the StartXRD.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                            #
##############################################################################

Debug () {
    if test $VERBOSE -eq 1; then
       /bin/echo $1
    fi
    }

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

Terminate() {
    xrdpid=$1

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

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

Check(){
    xrdpid=$1

    # Check if the process is indeed dead
    #
      FOO=`/bin/ps -p $xrdpid`
      if [ $? -eq 0 ]; then
         sleep 1
         FOO=`/bin/ps -p $xrdpid`
         if [ $? -eq 0 ]; then
         /bin/echo "pid $xrdpid 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
        Notify "Invalid option '$1'."
     fi
   shift
   done

# find the process number assigned to the XRD
#
  set -- `/bin/ps -e -o pid -o args | /bin/grep /opt/xrootd/ | /bin/grep /bin/xrootd | /bin/grep -v grep | /bin/awk '{print $1}'`

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

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

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

  /bin/echo StopXRD: XRD stopped.
