#!/sbin/runscript
# Copyright 1999-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License, v2 or later
# $Header: /var/cvsroot/gentoo-x86/sys-cluster/gnbd/files/gnbd-client.rc,v 1.5 2005/10/07 19:48:57 xmerlin Exp $

depend() {
	use dns logger
	need net
	need fenced
}

load_modules() {
	local module modules
	modules=$1
	
	for module in ${modules}; do
		ebegin "Loading ${module} kernel module"
		modprobe ${module}
		eend $? "Failed to load ${module} kernel module"
	done
}

unload_modules() {
	local module modules
	modules=$1
	
	for module in ${modules}; do
		ebegin "Unloading ${module} kernel module"
		modprobe -r ${module}
		eend $? "Failed to unload ${module} kernel module"
	done
}


start() {
	if [ ! -f /etc/gnbdtab ] ; then
		eerror "Please create /etc/gnbdtab"
		eerror "Sample conf: /etc/gnbdtab"
		return 1
	fi

	load_modules gnbd
	
	GNBD=`cat /etc/gnbdtab | egrep '^import'`
	if [ -n "$GNBD" ] ; then
		ebegin "Importing all GNBDs devices"
		einfo "$(awk '/^import/ { print "--> server:", $2 }' /etc/gnbdtab )"
		cat /etc/gnbdtab | awk '/^import/ { print "-i", $2 }' | xargs -l gnbd_import ${GNBD_CLIENT_OPTS} > /dev/null
		eend $? "Failed to import gnbd devices"
	fi
}

stop() {

	# umount manually mounted gfs filesystems
	local sig retry
	local remaining="$(awk '$3 ~ /gfs/ && $1 ~ /\/dev\/gnbd\// { if ($2 != "/") print $2 }' /proc/mounts | sort -r)"

	if [ -z "${remaining}" ]
	then
		ebegin "Unmounting GFS filesystems (GNBDs imported devices)"
		eend 0
	else
	        sig=
	        retry=3
	        while [ -n "${remaining}" -a "${retry}" -gt 0 ]
	        do
	                if [ "${retry}" -lt 3 ]
			then
	                        ebegin "Unmounting GFS filesystems (retry)"
	                        umount ${remaining} &>/dev/null
	                        eend $? "Failed to unmount GFS filesystems this retry"
	                else
	                        ebegin "Unmounting GFS filesystems"
	                        umount ${remaining} &>/dev/null
	                        eend $? "Failed to unmount GFS filesystems"
	                fi
	                remaining="$(awk '$3 ~ /gfs/ && $1 ~ /\/dev\/gnbd\// { if ($2 != "/") print $2 }' /proc/mounts | sort -r)"
	                [ -z "${remaining}" ] && break
	                /bin/fuser -k -m ${sig} ${remaining} &>/dev/null
	                sleep 5
	                retry=$((${retry} -1))
	                sig=-9
	        done
	fi

	local GNBD_MONITOR_PROC

	ebegin "Unimporting all GNBDs devices"
	gnbd_import -q -R &> /dev/null
	eend $?

	GNBD_MONITOR_PROC="$(pgrep gnbd_clusterd)"
	if [ -n "${GNBD_MONITOR_PROC}" ]; then
		ebegin "Stopping gnbd_monitor"
		killall gnbd_monitor &> /dev/null
		eend $?
	fi
	
	unload_modules gnbd
}
