#! /bin/sh
#
# portmap       Start/Stop RPC portmapper
#
# chkconfig: 345 11 89
# description: The portmapper manages RPC connections, which are used by \
#              protocols such as NFS and NIS. The portmap server must be \
#              running on machines which act as servers for protocols which \
#              make use of the RPC mechanism.
# processname: portmap
#
### BEGIN INIT INFO
# Provides: $portmap
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 4 5
# Short-Description: RPC portmapper
# Description: The portmapper manages RPC connections, which are used by
#              protocols such as NFS and NIS. The portmap server must be
#              running on machines which act as servers for protocols which
#              make use of the RPC mechanism.
### END INIT INFO

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

# Get network configuration
. /etc/sysconfig/network

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

# Set defaults and load configuration
MAX=5
TIMEOUT=5
NAME=portmap
LOCKFILE=/var/lock/subsys/portmap
[ -f /etc/sysconfig/portmap ] && . /etc/sysconfig/portmap

if [ -n "$PORTMAP_IP_OR_HOSTNAME" ]; then
    PORTMAPARG="-i $PORTMAP_IP_OR_HOSTNAME"
else
    PORTMAPARG=""
fi

function check_network() {
    route -n | grep -q ^0\.0\.0\.0
}

function start() {
    res=0
    if [ ! -f $LOCKFILE ]; then
	num=0
	gprintf "Starting %s:" "$NAME"
	while [ -n "$PORTMAP_IP_OR_HOSTNAME" ] && ! check_network && [ $num -lt $MAX ]; do
	    sleep $TIMEOUT
	    num=$(($num + 1))
	done
	daemon portmap $PORTMAPARG
	res=$?
	echo
	[ $res -eq 0 ] && touch $LOCKFILE
    fi
    return $res
}

function stop() {
    gprintf "Stopping %s:" "$NAME"
    killproc portmap
    res=$?
    echo
    [ $res -eq 0 ] && rm -f $LOCKFILE
    return $res
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
	status portmap
	;;
    restart|reload)
	stop
	start
	;;
    *)
	gprintf "Usage: %s {start|stop|status|restart|reload}\n" "$0"
	exit 1
	;;
esac

exit $?
