#! /bin/sh

### BEGIN INIT INFO
# Provides:          global network block device server
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start and stop the gnbd server
### END INIT INFO


PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/gnbd_serv
NAME=gnbd_serv
DESC="global network block device server"

test -x $DAEMON || exit 0

GNBD_OPTIONS=""

if [ -f /etc/default/gnbd-server ] ; then
	. /etc/default/gnbd-server
fi

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
	if grep -q '^/' /etc/cluster/gnbdexports.conf; then
		start-stop-daemon --start --quiet --pidfile /var/run/gnbd/$NAME.pid --exec $DAEMON -- $GNBD_OPTIONS
		echo "Exporting device(s):"
		grep -v "^#" /etc/cluster/gnbdexports.conf | grep -v "^[:space:]*$" | \
		while read device name options; do
			gnbd_export -d $device -e $name $options
		done
		echo "done."
	else
		echo "No configured exports."
	fi
	;;
  stop)
	if [ -e /var/run/gnbd/$NAME.pid ]; then
		echo -n "Unexporting device(s): "
		gnbd_export -R
		echo "done."
		echo -n "Stopping $DESC: "
		start-stop-daemon --stop --quiet --pidfile /var/run/gnbd/$NAME.pid --exec $DAEMON
		rm -f /var/run/gnbd/$NAME.pid
		echo "$NAME."
	else
		echo "Stopping $DESC: is not running."
	fi
	;;
  restart|force-reload)
	echo -n "Restarting $DESC: "
	$0 stop
	sleep 1
	$0 start
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
