#!/bin/bash
#
# enbd-client	Start/Stop the Enhanced Network Block Device client daemon
#
# Author:	Steve Purkis <steve.purkis@multimap.com>
#		(derived work)
# Originals by:	Peter T. Breuer <ptb@it.uc3m.es>
#		Matthew Sackman <matthew@wellquite.org>
# License:	GNU GPL v2.1
#
# These scripts are for Red Hat machines.
#
# chkconfig: 2345 80 20
# description: ENBD Client Daemon
# processname: enbd-client
# config: this file
# pidfile: /var/run/enbd-client-$CLIENT_ID.pid

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

prog="enbd-client"
pidfile="/var/run/enbd-client-$CLIENT_ID.pid"

ENBD_CLIENT="/usr/local/sbin/enbd-client"
ENBD_CLIENT_LOG="/var/log/enbd-client"
SERVER="p4test2.multimap.com:1100"
LOCAL_DEVICE="/dev/nda"
CLIENT_ID=`uname -n | cut -f1 -d.`
CLIENT_OPTS="-i $CLIENT_ID -n 2"

start() {
	echo -n "Starting $prog: "

	modprobe enbd
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		failure
		echo
		return $RETVAL
	fi

	$ENBD_CLIENT $SERVER $CLIENT_OPTS $LOCAL_DEVICE >$ENBD_CLIENT_LOG 2>&1 && success || failure

	RETVAL=$?
	echo

	return $RETVAL
}

stop() {
	status $prog
	ALIVE=$?

	if [ $ALIVE -eq 0 ]; then
		echo -n "Stopping $prog: "
		killproc $prog
		RETVAL=$?
		echo
		error_out_nbd_requests
	else
		RETVAL=0
	fi

	return $RETVAL
}

error_out_nbd_requests() {
	echo -n "Removing pending requests on nbd devices"
	echo -n "0" > /proc/nbdinfo
	COUNTER=0
	while [ $COUNTER -lt 10 ]; do
		# TODO: would be better to do some sort of check, rather than
		#       just sleeping for 10s!
		echo -n "."
		let COUNTER=COUNTER+1
		sleep 1
	done
	echo -n "0" > /proc/nbdinfo
	echo
}

hardstop() {
	echo -n "Killing $prog: "
	killproc -KILL $prog
	RETVAL=$?
	echo
	return $RETVAL
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  hardstop)
  	hardstop
	;;
  restart)
	stop
	start
	;;
  status)
	status $prog
	;;
  *)
	echo "Usage: $0 {start|stop|hardstop|restart|status}"
	exit 1
esac

exit $?
