#! /bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/sbin/clvmd
NAME=clvmd
DESC="Cluster LVM Daemon"

test -x $DAEMON || exit 0

if [ -f /etc/default/clvm ] ; then
	. /etc/default/clvm
fi

[ -n "$CLVMDTIMEOUT" ] || CLVMDTIMEOUT=60

if [ ! -f /etc/cluster/cluster.conf ]; then
	echo "clvmd: cluster not configured. Aborting."
	exit 0
fi

if ! cman_tool status >/dev/null; then
	echo "clvmd: cluster is not running. Aborting."
	exit 0
fi

set -e

wait_for_nodes() {
	vgscan > /dev/null 2>&1
	wait=0
	while [ -n "$(vgchange -a y 2>&1 |grep "clvmd not running")" ]; do
		if [ $wait -lt $CLVMDTIMEOUT ]; then
			echo "clvmd: Waiting for other nodes to join the cluster.."
			sleep 3
			wait=$(($wait + 3))
		else
			echo "failed."
			exit 1
		fi
	done
	echo "done."
	exit 0
}

case "$1" in
  start)
	echo -n "Starting $DESC "
	if start-stop-daemon --start --quiet --exec $DAEMON -- $DAEMON_OPTS; then
		wait_for_nodes
	fi
	;;
  stop)
	echo -n "Stopping $DESC "
	start-stop-daemon --stop --oknodo --quiet --exec $DAEMON
	echo "done."
	;;
  reload|restart|force-reload)
	echo -n "Restarting $DESC "
	start-stop-daemon --stop --oknodo --quiet --exec $DAEMON
	sleep 1
	if start-stop-daemon --start --oknodo --quiet --exec $DAEMON -- $DAEMON_OPTS; then
		wait_for_nodes
	fi
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac

exit 0
