#!/bin/bash
#
# chkconfig: - 24 76
# description: Starts and stops clvmd
#
# For Red-Hat-based distributions such as Fedora, RHEL, CentOS.
#	       
### BEGIN INIT INFO
# Provides: clvmd
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start:
# Default-Stop: 0 1 6
# Short-Description: Clustered LVM Daemon
### END INIT INFO

. /etc/init.d/functions

DAEMON=clvmd

exec_prefix=@exec_prefix@
sbindir=@sbindir@

LVDISPLAY=${sbindir}/lvdisplay
VGCHANGE=${sbindir}/vgchange
VGSCAN=${sbindir}/vgscan
VGDISPLAY=${sbindir}/vgdisplay
VGS=${sbindir}/vgs

CLVMDOPTS="-T20"

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

[ -n "$CLVMD_CLUSTER_IFACE" ] && CLVMDOPTS="$CLVMDOPTS -I $CLVMD_CLUSTER_IFACE" 

LOCK_FILE="/var/lock/subsys/$DAEMON"

start()
{
	for rtrn in 0
	do
		if ! pidof $DAEMON > /dev/null 
		then 
			echo -n "Starting $DAEMON: "
			daemon $DAEMON $CLVMDOPTS
			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
				action "Activating VG $vg:" $VGCHANGE -ayl $vg || rtrn=$?
			done
		else
			action "Activating VGs:" $VGCHANGE -ayl || rtrn=$?
		fi
	done

	return $rtrn
}

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

		[ $rtrn -ne 0 ] && break

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

wait_for_finish()
{
	count=0

	while [ "$count" -le 10 -a -n "`pidof $DAEMON`" ]
	do
		sleep 1
		count=$((count + 1))
	done
	
	if [ `pidof $DAEMON` ]
	then
		return 1
	else
		return 0
	fi
}

reload() {
	$DAEMON -R
}

rh_status() {
	status $DAEMON
}

rh_status_q() {
	rh_status >/dev/null 2>&1
}


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
		wait_for_finish
		start
	fi 
	rtrn=$?
	;;

  reload)
	rh_status_q || exit 7
	reload
	;;

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

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

exit $rtrn
