#!/bin/bash
#
# gfs mount/unmount helper 
#
# chkconfig: - 26 74
# description: mount/unmount gfs filesystems configured in /etc/fstab

### BEGIN INIT INFO
# Provides:		gfs
# Required-Start:	$network cman
# Required-Stop:	$network cman
# Default-Start:
# Default-Stop:
# Short-Description:	mount/unmount gfs filesystems configured in /etc/fstab
# Description:		mount/unmount gfs filesystems configured in /etc/fstab
### END INIT INFO

# set secure PATH
PATH="/bin:/usr/bin:/sbin:/usr/sbin:/usr/sbin"

success()
{
    echo -ne "[  OK  ]\r"
}

failure()
{
    echo -ne "[FAILED]\r"
}

# rpm based distros
if [ -d /etc/sysconfig ]; then
	[ -f /etc/rc.d/init.d/functions ] && . /etc/rc.d/init.d/functions
	[ -f /etc/sysconfig/cluster ] && . /etc/sysconfig/cluster
	[ -f /etc/sysconfig/gfs ] && . /etc/sysconfig/gfs
	[ -z "$LOCK_FILE" ] && LOCK_FILE="/var/lock/subsys/gfs"
fi

# deb based distros
if [ -d /etc/default ]; then
	[ -f /etc/default/cluster ] && . /etc/default/cluster
	[ -f /etc/default/gfs ] && . /etc/default/gfs
	[ -z "$LOCK_FILE" ] && LOCK_FILE="/var/lock/gfs"
fi

#
# This script's behavior is modeled closely after the netfs script.  
#
GFSFSTAB=$(LC_ALL=C awk '!/^#/ && $3 == "gfs" && $4 !~ /noauto/ { print $2 }' /etc/fstab)
GFSMTAB=$(LC_ALL=C awk '!/^#/ && $3 == "gfs" && $2 != "/" { print $2 }' /proc/mounts)

# See how we were called.
case "$1" in
  start)
        if [ -n "$GFSFSTAB" ] 
	then
		echo -n "Mounting GFS filesystems: "
		mount -a -t gfs
		rtrn=$?
		if [ $rtrn = 0 ]; then
			touch $LOCK_FILE
			success
			echo
		else
			failure
			echo
		fi
	fi
	;;

  stop)
  	if [ -n "$GFSMTAB" ] 
	then
		sig=
		retry=6
		remaining=`LC_ALL=C awk '!/^#/ && $3 == "gfs" && $2 != "/" {print $2}' /proc/mounts`
		while [ -n "$remaining" -a "$retry" -gt 0 ]
		do
			echo -n "Unmounting GFS filesystems: "
			umount -a -t gfs
			rtrn=$?
			if [ $rtrn = 0 ]; then
				success
				echo
			else
				failure
				echo
			fi

			if [ $retry -eq 0 ] 
			then
				echo -n "Unmounting GFS filesystems (lazy): "
				umount -l -a -t gfs
				rtrn=$?
				if [ $rtrn = 0 ]; then
					success
					echo
				else
					failure
					echo
				fi
				break
			fi

			sleep 2
			remaining=`LC_ALL=C awk '!/^#/ && $3 == "gfs" && $2 != "/" {print $2}' /proc/mounts`
			[ -z "$remaining" ] && break
			fuser -k -m $sig $remaining > /dev/null 2>&1
			sleep 10
			retry=$(($retry - 1))
			sig=-9
		done
	fi

	modprobe -r gfs
	rm -f $LOCK_FILE
	;;

  status)
	if [ -f /proc/mounts ]
	then
	        [ -n "$GFSFSTAB" ] && {
		     echo "Configured GFS mountpoints: "
		     for fs in $GFSFSTAB; do echo $fs ; done
		}
		[ -n "$GFSMTAB" ] && {
                      echo "Active GFS mountpoints: "
		      for fs in $GFSMTAB; do echo $fs ; done
		}
	else
		echo "/proc filesystem unavailable"
	fi
	;;

  restart)
	$0 stop
	$0 start
	;;

  reload|force-reload)
        $0 start
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|reload|status}"
	exit 1
esac

exit 0
