#!/bin/bash
#
# drbd_sync     This shell script ensures all drbd resources are synced
#
# chkconfig: 345 71 9
# description: ensures all drbd resources are synced
### BEGIN INIT INFO
# Provides: drbd_sync
# Required-Start: $network $syslog sshd drbd
# Required-Stop: $network $syslog sshd drbd
# Default-Start:  3 4 5
# Default-Stop:   0 1 2 6
# Short-Description:    Sync drbd resources.
### END INIT INFO
#

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

MODPROBE="/sbin/modprobe"
DRBDADM="/sbin/drbdadm"
DRBDSETUP="/sbin/drbdsetup"
RETVAL=0
OPTIONS=""

handle_error() {
	ERROR=$1
	while true; do echo $ERROR; sleep 60 ; done
}

start() {
	echo -n "Waiting for DRBD resources to sync: "
	$MODPROBE -n drbd >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		handle_error "DRBD Sync Error: DRBD Module is not loaded"
	fi
	RESOURCES=$($DRBDADM sh-resources all)
	if [ $? -ne 0 ]; then
		handle_error "DRBD Sync Error: DRBD configuration has errors"
	fi
	for RESOURCE in $RESOURCES; do
		DEV=$($DRBDADM sh-dev $RESOURCE)
		CSTATE=$($DRBDSETUP $DEV cstate)
		DSTATE=$($DRBDSETUP $DEV dstate  | cut -f 1 -d /)
		SYNCING=$(echo $CSTATE | grep -Ei "Sync" | wc -w)
		if [ $SYNCING -ne 0 ] && [ $DSTATE != "UpToDate" ]; then
			echo -n "$RESOURCE "
			$DRBDSETUP $DEV wait-sync 
		fi
	done
	echo -n " - Done"
	RETVAL=$?
	return $RETVAL
}

stop() {
	# Do nothing
	return 0
}

status() {
	# Do nothing
	return 0
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart|reload)
        stop
        start
        RETVAL=$?
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit $RETVAL
