#!/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:   StopXRD

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

CONDCHK=0

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

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

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

Terminate() {
    xrdpid=$1

    # Verify that we can kill this process
    #
      if [ $MYNAME != root ]; then
         set -- `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 -- `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=`ps -p $xrdpid`
      if [ $? -eq 0 ]; then
         sleep 1
         FOO=`ps -p $xrdpid`
         if [ $? -eq 0 ]; then
         echo "pid $xrdpid is still alive..."
         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 -- `ps -e -o pid -o comm | grep '.*xrootd$' | 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
     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

  echo StopXRD: XRD stopped.
