#!/bin/bash

# Start only if at least on xinetd based service
# is activated

test "$(ls -A ###ROOT###/etc/xinetd.d/)" || exit 5

PIDFILE=###ROOT###/tmp/run/xinetd.pid
DAEMON=/usr/sbin/xinetd
OPTS="-pidfile ###ROOT###/tmp/run/xinetd.pid -filelog ###ROOT###/var/log/xinetd.log -f ###ROOT###/etc/xinetd.conf"

case "$1" in
    start)
 	echo -n 'Starting xinetd...'
	if [ -e "$PIDFILE" ] ; then
	    PID=$(cat $PIDFILE)
	    if [ -n "$PID" ] && ps $PID > /dev/null 2>&1 ; then
		echo "still running with pid $PID! Aborting!"
		exit 1
	    fi
	    echo "removing stale pid file..."
	    rm -f $PIDFILE
	fi

        # Do not use usual system daemon path. Some start script
        # (e.g. SLES) will think that the system xinetd is already
        # running and do not start it if the OMD xinetd is running.
        mkdir -p $OMD_ROOT/var/tmp
        cp $DAEMON $OMD_ROOT/var/tmp/xinetd
        $OMD_ROOT/var/tmp/xinetd $OPTS
        echo OK
    ;;
    stop)
	echo -n 'Stopping xinetd...'
        PID=$(cat $PIDFILE 2>/dev/null)
        if [ -z "$PID" ] ; then
	    echo "not running."
        elif kill "$PID" ; then
	    echo "OK"
        else
	    echo "Failed"
        fi
        rm -f $OMD_ROOT/var/tmp/xinetd
    ;;
    restart)
	$0 stop
	$0 start
    ;;
    reload)
	echo -n 'Reloading xinetd...'
	if [ -e "$PIDFILE" ] ; then
	    PID=$(cat $PIDFILE)
	    if kill -HUP $PID
	    then
		echo OK
	    else
		echo ERROR
		exit 1
	    fi
	else
	    echo "not running"
	    exit 1
        fi
    ;;
    status)
	echo -n 'Checking status of xinetd...'
	if [ -e "$PIDFILE" ] ; then
	    PID=$(cat $PIDFILE)
	    if [ -n "$PID" ] && ps $PID > /dev/null 2>&1 ; then
		echo "running"
		exit 0
	    fi
	fi
	echo "stopped"
	exit 1
    ;;
    *)
	echo "Usage: $0 {start|stop|restart|reload|status}"
    ;;
esac
