#!/bin/bash
#
# chkconfig: 345 23 77
# description: import gnbd devices from servers specified \
# by GNBD_SERVERS in /etc/sysconfig/gfs
#              
#
### BEGIN INIT INFO
# Provides: 
### END INIT INFO

. /etc/init.d/functions
. /etc/init.d/gfs-functions
[ -f /etc/sysconfig/gfs ] && . /etc/sysconfig/gfs

# do not start if there are no servers configured
[ -z "$GNBD_SERVERS" ] && exit 0

find_master()
{
        gulm_master=""
        line=$(gulm_tool getstats localhost 2>/dev/null |
                awk 'BEGIN{xit=1}
                        ($1 == "I_am"){xit=0}
                        ($0 ~ /^(I_am = Master|Master =)/) {print}
                        END{exit xit}')
        [ $? -ne 0 ] && return 1

        case $line in
                I_am\ =\ Master)
                        gulm_master=$(hostname)
                        ;;
                Master\ =*)
                        server=${line#*= }

                        if gulm_tool getstats $server 2>/dev/null |
                                grep -q "I_am = Master"
                        then
                                gulm_master=$server
                        fi
                        ;;
                *) ;;
        esac

        [ -n "$gulm_master" ]
}


start()
{
	if ! find_master 
	then
		echo "no master gulm server found"
		return 1
	fi

	sts=0
	for server in $GNBD_SERVERS
	do
		gnbd_import -i $server || sts=1
	done

	# 
	# Pool probably needs to be restarted if it is to use
	# of newly imported gnbd devices.  
	# 
	/etc/init.d/pool restart

	return $sts
}

stop()
{
	sts=0
	
	#
	# Need to make sure that pool isn't running on top of gnbd
	#
	/etc/init.d/pool stop

	# if netfs can umount mount points not in /etc/fstab, we should 
	# be able to remove any gnbd device that is currently imported :)
	gnbd_import -R || sts=1

	return $sts
}	

status()
{
	sts=0
	gnbd_import -l
	return $sts
}

rtrn=1

# Simply exit if there are no GNBD_SERVERS listed.  Command line 
# are not checked if there are no servers.
[ -z "$GNBD_SERVERS" ] && exit 0

# See how we were called.
case "$1" in
  start)
	# Make sure that ccsd is running 
	if ! ccs_read list 2>/dev/null >/dev/null 
	then
                echo ccsd is not responding
                exit 0
	fi

	load_module lock_harness MODULE_LOCK_HARNESS
	load_module crc32	 MODULE_CRC32
	load_module lock_gulm    MODULE_LOCK_GULM
	load_module gnbd	 MODULE_GNBD
	start
	rtrn=$?
	[ $rtrn -eq 0 ] && touch /var/lock/subsys/gnbd_import
	;;

  stop)
	stop 
	rtrn=$?
	[ $rtrn -eq 0 ] && rm -f /var/lock/subsys/gnbd_import
	unload_module gnbd 	   > /dev/null 2>&1
	unload_module lock_gulm    > /dev/null 2>&1
	unload_module crc32	   > /dev/null 2>&1
	unload_module lock_harness > /dev/null 2>&1
	;;

  restart)
	$0 stop
	$0 start
	rtrn=$?
	;;

  status)
	status
	rtrn=0
	;;

  *)
	echo $"Usage: $0 {start|stop|restart|status}"
	;;
esac

exit $rtrn

