#!/bin/sh
#
# chkconfig: 345 30 70
# description: Loads and unloads the drbd module
#
# Copyright (C) 1999 2000, Philipp Reisner <philipp@linuxfreak.com>.
# Initial author.
#
# Copyright (C) 2000, Fbio Oliv Leite <olive@conectiva.com.br>
# Changes to support multiple devices and different distributions.
# Changes to increase robustness and exit with proper error values.
#
# Some ideas and inspiration from Joe Hartley <jh@brainiac.com>

# Source function library.

export INSTALL="/etc/ha.d/resource.d"
. $INSTALL/drbd_common $*

# If the distribution does not have sysconfig/network, let's hope
# networking is up.
# TM : I don't like to hope stop if not here . Will add distro specif code.
# Removed as suse don't have this directory

# have_file /etc/sysconfig/network

if [ "$NETWORKING" = "no" ]; then
	echo "$0 : The network is not accessible"
	exit 1
fi

# Check for drbd's module
if [ ! -f /lib/modules/`uname -r`/block/drbd.o ]; then
	echo "$0 : module not found. did you upgraded your kernel ?"
	exit 1
fi

# See how we were called.
case "$OPTION" in
	# Start the service
	start)
		INSERTED=`lsmod | grep drbd | wc -l | sed -e s/\ //g`

		if [ "$INSERTED" -eq 0 ]; then
			MINOR_COUNT=`echo $DEVICES | wc -w | sed -e s/\ //g`
			action "Loading DRBD module " \
			modprobe -s drbd minor_count=$MINOR_COUNT 2> /dev/null

			if [ $? -eq 1 ]; then
				exit 1
			fi
		else
			succed "DRBD module is already inserted"
		fi

		if [ -z "$RESOURCE" ]; then
			runForAll configure
			exit $RETVAL
		else
			$0 $RESOURCE configure
		fi

		;;

	# internal start sub function
	configure)
		setLocal $CONFIG $RESOURCE

		have_device $LOCAL_DEVICE

		action "Configuring DRBD resource $RESOURCE" \
			drbdsetup $LOCAL_DEVICE $LOCAL_PARTITION \
			$PROTOCOL $LOCAL_IF $REMOTE_IF $OPTIONS 2> /dev/null

		RV=$?
		[ $RETVAL -eq 0 ] && RETVAL=$RV

		isMasterBoot $RESOURCE
		if [ ! $? ]; then
			if [ $RV -eq 0 ]; then
				echo -n "Connection to master in 10 seconds"
				sleep 10
				success

				action "resynchronizing resource $RESOURCE" \
					drbdsetup $LOCAL_DEVICE WAIT
			else
					succed "Node is slave nothing to sync"
			fi
		fi
		;;

	stop)
		INSERTED=`lsmod | grep drbd | wc -l`

		if [ "$INSERTED" -eq 1 ]; then
			action "Unloading DRBD module" rmmod -s drbd
			RETVAL=$?
		else
			succed "DRBD module was not loaded"
		fi
		;;

	restart)
		$0 stop
		$0 start
		RETVAL=$?
		;;
	
	status)
		$INSTALL/drbdc proc
		RETVAL=$?
		;;
	*)
		echo "Usage: $0 [resource] {start|stop|restart|status}"
		RETVAL=1
		;;
esac

exit $RETVAL

