#!/bin/bash
#
# chkconfig: 345 24 76
# description: Starts and stops clvmd
#
#	       
### BEGIN INIT INFO
# Provides: 
### END INIT INFO

. /etc/init.d/functions

LVDISPLAY="/usr/sbin/lvdisplay"
VGCHANGE="/usr/sbin/vgchange"
VGSCAN="/usr/sbin/vgscan"
VGDISPLAY="/usr/sbin/vgdisplay"
VGS="/usr/sbin/vgs"

[ -f /etc/sysconfig/cluster ] && . /etc/sysconfig/cluster

LOCK_FILE="/var/lock/subsys/clvmd"

start()
{
	for rtrn in 0
	do
		if ! pidof clvmd > /dev/null 
		then 
			echo -n "Starting clvmd: "
			daemon clvmd
			rtrn=$?
			echo
			if [ $rtrn -ne 0 ]
			then
				break
			fi
 		fi	
		# refresh cache
		$VGSCAN  > /dev/null 2>&1
		
		if [ -n "$LVM_VGS" ]
		then
			for vg in $LVM_VGS
			do
				if ! action "Activating VG $vg:" $VGCHANGE -ayl $vg
				then
					rtrn=$?
                                fi
			done
		else
			if ! action "Activating VGs:" $VGCHANGE -ayl
			then
				rtrn=$?
                        fi
		fi
	done

	return $rtrn
}

stop()
{
	for rtrn in 0
	do
		if [ -n "$LVM_VGS" ]
		then
			for vg in $LVM_VGS
			do
				if ! action "Deactivating VG $vg:" $VGCHANGE -anl $vg
				then
					rtrn=$?
				fi
			done
		else
			# Hack to only deactivate clustered volumes
		        clustervgs=`$VGDISPLAY \`$VGS --noheadings -o name\` | awk 'BEGIN {RS="VG Name"} {if (/Clustered/) print $1;}'`
			for vg in $clustervgs; do
				if ! action "Deactivating VG $vg:" $VGCHANGE -anl $vg
				then
					rtrn=$?
				fi
			done
		fi

		[ $rtrn -ne 0 ] && break

		echo -n "Stopping clvm:"
		killproc clvmd -TERM
		rtrn=$?
		echo
	done
	
	return $rtrn
}

rtrn=1

# See how we were called.
case "$1" in
  start)
	start
	rtrn=$?
	[ $rtrn = 0 ] && touch $LOCK_FILE
	;;

  stop)
	stop
	rtrn=$?
	[ $rtrn = 0 ] && rm -f $LOCK_FILE
	;;

  restart)
	if stop
	then
		start
	fi 
	rtrn=$?
	;;

  status)
	status clvmd
	rtrn=$?
	vols=$( $LVDISPLAY -C --nohead 2> /dev/null | awk '($3 ~ /....a./) {print $1}' )
	echo active volumes: ${vols:-"(none)"}
	;;

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

exit $rtrn
