#!/bin/sh
#
# xorp		This shell script takes care of starting and stopping
#		the Open Router Platform XORP.
#
# chkconfig: - 84 16
#
# description:	XORP is the eXtensible Open Router Platform
# processname:	xorp_rtrmgr
# config:	/etc/xorp/xorp.conf
# pidfile:	/var/run/xorp_rtrmgr.pid
#
### BEGIN INIT INFO
# Provides:          xorp
# Required-Start:    $network $local_fs
# Required-Stop:
# Should-Start:      $named
# Should-Stop:
# Default-Start:
# Default-Stop:      0 1 6
# Short-Description: eXtensible Open Router Platform
# Description:       XORP is the eXtensible Open Router Platform. It
#                    implements a number of network protocols such as BGP,
#                    OSPF, RIP/RIPng, IGMP/MLD and PIM-SM.
### END INIT INFO


# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 1

# Source function library.
. /etc/init.d/functions

PROG=xorp_rtrmgr
EXEC=/usr/sbin/${PROG}
CONF=/etc/xorp/xorp.conf
LOGF=/var/log/xorp/${PROG}.log

# Check for binaries and configs
[ -x ${EXEC} ] || exit 5
[ -f ${CONF} ] || exit 6

# Include config
if [ -s /etc/sysconfig/${PROG} ]; then
  . /etc/sysconfig/${PROG}
fi

# Further defines
XORP_CONF="${BOOT_CONF:-${CONF}}"
XORP_LOGF="${XORP_LOGF:-${LOGF}}"
XORP_TMPL="${XORP_TMPL:-/usr/share/xorp/templates}"
XORP_SHUT="${XORP_SHUT:-100}"

PIDFILE=/var/run/${PROG}.pid
LOCKFILE=/var/lock/subsys/${PROG}
RETVAL=0

start()
{
	start_daemon --pidfile "${PIDFILE}" --lockfile "${LOCKFILE}" --expect-user root -- ${EXEC} \
		-d -l ${XORP_LOGF} -P ${PIDFILE} -b ${XORP_CONF} -t ${XORP_TMPL} ${OPTIONS}
	RETVAL=$?
	return ${RETVAL}
}

stop()
{
# stop_daemon() can't be used: xorp_rtrmgr stops processes long time
	msg_stopping "${PROG}"
	
	PID=`pidof -o %PPID ${PROG}`
	RETVAL=$?
	
	[ ${RETVAL} -eq 0 ] && {
		kill -TERM ${PID}

		TIMEOUT=0
		while pidof -o %PPID ${PROG} >/dev/null; do
			if [ ${TIMEOUT} -ge ${XORP_SHUT} ]; then
				RETVAL=1
				failure "${PROG} is not stopped in ${TIMEOUT} seconds,"
				break
			else
				sleep 5 && echo -n "."
				TIMEOUT=$((TIMEOUT+5))
			fi
		done

		[ ${RETVAL} -eq 0 ] && rm -f ${PIDFILE} ${LOCKFILE}
	} || failure "${PROG} is not running,"

	[ ${RETVAL} -eq 0 ] &&  success "${PROG} stopped in ${TIMEOUT} seconds,"

	echo
	return ${RETVAL}
}

restart()
{
	stop
	start
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	condstop)
		if [ -e "${LOCKFILE}" ]; then
			stop
		fi
		;;
	condrestart|condreload)
		if [ -e "${LOCKFILE}" ]; then
			restart
		fi
		;;
	status)
		status --pidfile "${PIDFILE}" --expect-user root -- ${EXEC}
		RETVAL=$?
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit ${RETVAL}
