#!/bin/sh
#
# /etc/init.d/nis	Start NIS (formerly YP) daemons.
#
#

# Set to "false", "slave" or "master".
NISSERVER=false

NET="/usr/sbin"
test -f ${NET}/ypbind -a -f /etc/defaultdomain || exit 0

#
#	If ypbind broadcasts for the default domain, we may not be bound to 
#	any server yet (note that you can set broadcast in yp.conf for the
#	default domain without ypbind being run with -broadcast)
#
bind_wait()
{
	[ "`ypwhich 2>/dev/null`" = "" ] && sleep 1

	if [ "`ypwhich 2>/dev/null`" = "" ]
	then
		bound=""
		echo -n "[binding to YP server "
		for i in 1 2 3 4 5 6 7 8 9 10
		do
			sleep 1
			echo -n "."
			if [ "`ypwhich 2>/dev/null`" != "" ]
			then
				echo -n " done] "
				bound="yes"
				break
			fi
		done
		[ "$bound" ] || echo -n " backgrounded] "
	fi
}

start ()
{
	domainname `cat /etc/defaultdomain`
	echo "Setting NIS domainname to: `domainname`"
	echo -n "Starting NIS services: "
	if [ "$NISSERVER" != "false" ]
	then
		echo -n "ypserv "
		start-stop-daemon --start --quiet \
			--pidfile /var/run/ypserv.pid --exec ${NET}/ypserv
	fi
	if [ "$NISSERVER" = master ]
	then
		echo -n "yppasswdd "
		start-stop-daemon --start --quiet \
			--exec ${NET}/rpc.yppasswdd -- -e chsh
		echo -n "ypxfrd "
		start-stop-daemon --start --quiet \
			--exec ${NET}/rpc.ypxfrd
	fi
	if egrep -q '^(ypserver|domain)' /etc/yp.conf
	then
		broadcast=""
	else
		broadcast="-broadcast"
	fi
	echo -n "ypbind "
	start-stop-daemon -b --start --quiet --exec ${NET}/ypbind -- $broadcast
	bind_wait
	echo
}

stop () {
	start-stop-daemon --stop --quiet --oknodo \
		--pidfile /var/run/ypbind.pid --exec /usr/sbin/ypbind
	start-stop-daemon --stop --quiet --oknodo \
		--pidfile /var/run/ypserv.pid --exec /usr/sbin/ypserv
	start-stop-daemon --stop --quiet --oknodo \
		--exec /usr/sbin/rpc.yppasswdd
	start-stop-daemon --stop --quiet --oknodo \
		--exec /usr/sbin/rpc.ypxfrd
}

case "$1" in
  start)
	start;
	;;
  stop)
	stop
	;;
  reload|force-reload)
	start-stop-daemon --stop --quiet --oknodo --signal 1 \
		--pidfile /var/run/ypserv.pid --exec /usr/sbin/ypserv
	;;
  restart)
	stop
	sleep 2
	start
	;;
  *)
	echo "Usage: /etc/init.d/nis {start|stop|reload|force-reload|restart}"
	exit 1
esac

exit 0

