#!/bin/sh
#
# ypbind:	Starts the ypbind Daemon
#
# chkconfig:	345 42 63
#
# description:	This is a daemon which runs on NIS/YP clients and binds them \
#		to a NIS domain. It must be running for systems based on glibc \
#		to work as NIS clients, but it should not be enabled on systems \
#		which are not using NIS.
#
# processname:	ypbind
# config:	/etc/yp.conf


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

# Get network config
. /etc/sysconfig/network

# Get service config
[ -f /etc/sysconfig/ypbind ] && . /etc/sysconfig/ypbind

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "NIS client"
		exit 1
	fi
else
	exit 0
fi

if [ "$1" != "stop" ]; then
	check_portmapper || { nls "Error: portmap isn't running" && exit 0; }
fi

check_nisdomain()
{
	if [ -n "$NISDOMAIN" ]; then
		return 0
	else
		nls "Setup /etc/sysconfig/network::NISDOMAIN before use %s." ypbind >&2
		exit 6
	fi
}

start() {
	check_nisdomain
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/ypbind ]; then
		show "Binding to the NIS domain"
		daemon ypbind
		# the following fixes problems with the init scripts continuing
		# even when we are really not bound yet to a server, and then things
		# that need NIS fail.
		pid=`pidofproc ypbind`
		RETVAL=1
		if [ -n "$pid" ]; then
			show "Listening for a NIS domain server"
			times=0
			until ypwhich >/dev/null 2>&1 || [ "$times" = "10" ]; do
				echo -n "."
				sleep 1
				times=$((times + 1))
			done
			ypwhich
			if [ $? -ne 0 ]; then
				fail
				exit 1
			fi
			touch /var/lock/subsys/ypbind
			RETVAL=0
		fi
	else
		msg_already_running "NIS client"
	fi
}

stop() {
	check_nisdomain
	if [ -f /var/lock/subsys/ypbind ]; then
		msg_stopping "NIS client"
		killproc ypbind
		rm -f /var/lock/subsys/ypbind
		# if we used brute force (like kill -9) we don't want those around
		rm -f /var/yp/binding/$(domainname)*
	else
		msg_not_running "NIS client"
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  status)
	check_nisdomain
	status ypbind
	exit $?
	;;
  restart|force-reload)
	stop
	start
	;;
  condrestart)
	# NB! don't remove: dhcpcd calls this
	if [ -f /var/lock/subsys/ypbind ]; then
		stop
		start
	fi
  	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|condrestart|status}"
	exit 3
esac

exit $RETVAL
