#!/bin/sh
#
#	This script manages the status of ct_sync
#
#	"start" puts this node into master mode
#	"stop" puts this node into slave mode
#
#	Maximilian Wilhelm <max@rfc2324.org>
#	 -- Mon, 06 Mar 2006 04:48:31 +01000
#

# ct_sync state configuration
STATE_FILE="/proc/sys/net/ipv4/netfilter/ct_sync/state"
SYNCDEV_FILE="/etc/heartbeat/ct_sync.syncdev"


if [ ! -f "${STATE_FILE}" ]; then
	echo "Error: ct_sync not loaded..." >&2
	exit 1
fi

if [ ! -f "${SYNCDEV_FILE}" ]; then
	echo "Error: SYNCDEV_FILE \"${SYNCDEV_FILE}\" file not found." >&2
	exit 1
fi

function become_master() {
	echo 2 > "${STATE_FILE}"
	echo 1 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_be_liberal
}

function become_slave() {
	# If we were master, we could not just become a slave by re-seting the state
	# We *should* recognize the new master broadcast from the node which took over,
	# but we want to make things sure.

	# Forget about ct_sync
	/sbin/rmmod ct_sync

	# Get syncdev from config file.
	local syncdev=`cat "${SYNCDEV_FILE}"`
	/sbin/modprobe ct_sync syncdev=${syncdev}

	# Become slave (and hopefully resync automagically)
	echo 1 > "${STATE_FILE}"
	echo 1 > /proc/sys/net/ipv4/netfilter/ip_conntrack_tcp_be_liberal
}

function print_status() {

	local NUM_STATE=`cat "${STATE_FILE}"`
	local STATE=""

	case "${NUM_STATE}" in
		0)	STATE="not syncing."	;;
		1)	STATE="in slave mode."	;;
		2)	STATE="in master mode."	;;
		*)	STATE="Error. Unknown value." ;;
	esac

	echo "Current ct_sync state: ${STATE}"
}

case "${1}" in
	start)	become_master ;;
	stop)	become_slave ;;
	status)	print_status ;;
	*)
esac
