#!/bin/bash
#
# cmirrord - Clustered Mirrors Daemon init script
#
# chkconfig: - 22 78
# description: Clustered Mirror Daemon.
#
# For Red-Hat-based distributions such as Fedora, RHEL, CentOS.
#
### BEGIN INIT INFO
# Provides:		cmirrord
# Required-Start:	$network $time $local_fs
# Required-Stop:	$network $time $local_fs
# Short-Description:	This service is Clustered Mirrors Daemon.
# Description:		Daemon for device-mapper-based clustered mirrors.
### END INIT INFO

. /etc/rc.d/init.d/functions

DAEMON=cmirrord

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

[ -z "$CMIRRORD_STOP_TIMEOUT" ] && CMIRRORD_STOP_TIMEOUT=10

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

rh_status() {
	status $DAEMON
}

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

start()
{
	rh_status_q && return 0

	echo -n "Starting $DAEMON: "
	daemon $DAEMON || return $?
	echo

	touch $LOCK_FILE

	return 0
}

wait_for_finish()
{
	count=0
	while [ "$count" -le "$CMIRRORD_STOP_TIMEOUT" ] && \
		 rh_status_q ]; do
		sleep 1
		count=$((count+1))
	done

	! rh_status_q
}

stop()
{
	rh_status_q || return 0

	action "Signaling $DAEMON to exit" kill -TERM $(pidofproc $DAEMON) || return $?

	# wait half second before we start the waiting loop or we will show
	# the loop more time than really necessary
	usleep 500000

	# cmirrord could take some time to stop
	rh_status_q && action "Waiting for $DAEMON to exit:" wait_for_finish

	if rh_status_q; then
		echo -n "$DAEMON failed to exit"
		failure
		echo
		return 1
	else
		echo -n "$DAEMON terminated"
		success
		echo
	fi

	rm -f $LOCK_FILE

	return 0
}

restart() {
	stop && start
}

# See how we were called.
case "$1" in
  start)
	start
	rtrn=$?
	;;

  stop)
	stop
	rtrn=$?
	;;

  reload|restart|force-reload)
	restart
	rtrn=$?
	;;

  condrestart|try-restart)
	rh_status_q || exit 0
	restart
	rtrn=$? 
	;;

  status)
	rh_status
	rtrn=$?
	;;

  *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
	rtrn=2
	;;
esac

exit $rtrn
