#!/bin/sh
#
# Startup/shutdown script for services managed by xinetd.
#
#	Copyright (C) 2003 Charlie Brooks
#
#  WARNING:  tested ONLY on Red Hat 7.3 at this time.
#
# Author:	Charlie Brooks <ha@HBCS.Org>
# Description:	given parameters of a service name and start|stop|status,
#		will enable, disable or report on a specified xinetd service
# Config:	all services must have a descriptor file in /etc/xinetd.d
# Support:	Linux-HA mailing list -- http://linux-ha.org/contact/
# License:	GPL
#

VARRUN=/var/run
ETC=/etc
PIDFILE=$VARRUN/xup$1
XPIDFILE=$VARRUN/xinetd.pid
RCFILE=$ETC/xinetd.d/$1

# Source function library.
. $ETC/ha.d/shellfuncs

# It's important to note that the absence of a xinetd PID file causes
# this script to assume that xinetd is not yet running, and therefore
# that we are in the initial boot process.  If you port this script to
# a distro that keeps the pid files in some other place, be sure to 
# make an appropriate revision.

hup_inetd () {
    if [ -s $XPIDFILE ]; then
      if ! kill -HUP `cat $XPIDFILE`; then
          ha_log "ERROR: Could not SigHUP xinetd superdaemon!"
          ha_log "perhaps we are booting after a system crash"
          exit 2
      fi
    else
       ha_log "INFO: xinetd superdaemon PID file $XPIDFILE not found!"
       ha_log "perhaps we are currently booting the system."
fi
}

xup_start () {
  ha_log "info: $0: enabling in $RCFILE"
  if gawk '!/disable/' $RCFILE > $RCFILE.xup
    then
      if mv $RCFILE.xup $RCFILE
        then
          ha_log "info: $0: Starting"
          hup_inetd
          touch $PIDFILE
        else
          ha_log "ERROR: Could not replace $RCFILE"
      fi
    else
      ha_log "ERROR: Could not rewrite $RCFILE!"
  fi
}

xup_stop () {
  ha_log "info: $0: disabling in $RCFILE"
  if gawk '!/disable/;/{/{printf "\tdisable\t\t\t= yes\n"}' $RCFILE >$RCFILE.xup
    then
      if mv $RCFILE.xup $RCFILE
        then
          ha_log "info: $0: Shutting down"
          hup_inetd 
          rm -f $PIDFILE
        else
          ha_log "ERROR: Could not replace $RCFILE"
      fi
    else
      ha_log "ERROR: Could not rewrite $RCFILE!"
  fi
}

xup_usage () {
        echo "Usage: $0 {xinetd-service-name} {start|stop|restart|status}"
}

# Make sure the first parameter is a valid xinetd service name
if ! [ -f $RCFILE ]; then
    ha_log "ERROR:  Service descriptor /etc/xinetd.d/$1 not found!"
    xup_usage
    exit 1
fi

# See how we were called.
case "$2" in
  start)
	xup_start
	;;
  stop)
	xup_stop
	;;
  restart)
	$0 stop
	$0 start
	;;
  status)
  	if [ -f $PIDFILE ]; then
		echo running
	else
		echo stopped
	fi
	;;
  *)
	xup_usage
	exit 1
esac

exit 0
