#! /bin/bash
# We use some bashisms (arrays), so /bin/sh won't work.
# I hope this is policy-compliant; I couldn't find anything different,
# but if so, I'm gonna need help here to find a better way of handling
# this.
#
# skeleton	example file to build /etc/init.d/ scripts.
#		This file should be used to construct scripts for /etc/init.d.
#
#		Written by Miquel van Smoorenburg <miquels@cistron.nl>.
#		Modified for Debian GNU/Linux
#		by Ian Murdock <imurdock@gnu.ai.mit.edu>.
# 		Modified for the nbd-client package
#		by Wouter Verhelst <wouter@debian.org>
#
# Version:	@(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON="/bin/nbd-server"
NAME="nbd-server"
DESC="Network Block Device server"

test -f /etc/nbd-server && . /etc/nbd-server

test -x $DAEMON || exit 0

case "$1" in
  start)
	echo -n "Starting $DESC:"
	i=0
	while [ ! -z ${NBD_FILE[$i]} ]
	do
	  $DAEMON ${NBD_PORT[$i]} ${NBD_FILE[$i]} ${NBD_SERVER_OPTS[$i]} &
	  echo $! > /var/run/nbd-server.${NBD_PORT[$i]}.pid
	  echo -n " ${NBD_FILE[$i]}"
	  i=$(( $i + 1 ))
	done
	echo " $NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
        i=0
        echo -n "TERM "
        while [ ! -z ${NBD_FILE[$i]} ]
        do
          kill -TERM `cat /var/run/nbd-server.${NBD_PORT[$i]}.pid`
          echo -n " `cat /var/run/nbd-server.${NBD_PORT[$i]}.pid`"
          i=$(( $i + 1 ))
        done
        i=0
        sleep 1
        echo -n ", KILL "
        while [ ! -z ${NBD_FILE[$i]} ]
        do
          kill -KILL `cat /var/run/nbd-server.${NBD_PORT[$i]}.pid` 2>/dev/null
          echo -n " `cat /var/run/nbd-server.${NBD_PORT[$i]}.pid`"
          i=$(( $i + 1 ))
        done
        echo " $NAME."
	;;
  restart|force-reload)
	echo "Restarting the $DESC is pretty harsh on clients still using it."
	echo -n "waiting 5 seconds..."
	sleep 5
	echo "You have been warned!"
	echo -n "Restarting $DESC: "
	$0 stop
	sleep 10
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
