#!/bin/sh
#
#	$Id: $
#
#       OCF Resource Agent compliant script for WiKID
#
## BASED ON drbd script included with HA distribution:
##       $Id: drbd.in,v 1.24 2006/05/22 11:03:41 andrew Exp $
##
##       OCF Resource Agent compliant drbd resource script.
##
## WARNING: This is experimental code and still has a lot of open
## TODOs.
##
## Copyright (c) 2004 - 2005 SUSE LINUX Products GmbH, Lars Marowsky-Br�
##                    All Rights Reserved.
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it would be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Further, this software is distributed without any warranty that it is
# free of the rightful claim of any third person regarding infringement
# or the like.  Any license provided herein, whether implied or
# otherwise, applies only to this software file.  Patent licenses, if
# any, provided herein do not apply to combinations of this program with
# other software, or any other product whatsoever.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
#
#

# OCF instance parameters
#	OCF_RESKEY_wikid_resource
#	OCF_RESKEY_CRM_meta_clone_max
#	OCF_RESKEY_CRM_meta_clone_node_max
#	OCF_RESKEY_master_max
#	OCF_RESKEY_master_node_max


#######################################################################
# Initialization:

if [ -n "$OCF_DEBUG_LIBRARY" ]; then
	. $OCF_DEBUG_LIBRARY
else
	. $OCF_ROOT/resource.d/heartbeat/.ocf-shellfuncs
fi

#######################################################################

meta_data() {
	cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="wikid">
<version>1.1</version>

<longdesc lang="en">
OCF Resource Agent compliant wikid resource script
</longdesc>
<shortdesc lang="en">OCF Resource Agent compliant wikid resource script</shortdesc>

<parameters>
<parameter name="wikid_resource" unique="1" required="1">
<longdesc lang="en">
The name of the wikid resource from the wikid.conf file.
</longdesc>
<shortdesc lang="en">wikid resource name</shortdesc>
<content type="string" default="wikid0" />
</parameter>

<parameter name="clone_max" required="1">
<longdesc lang="en">
Number of clones of this wikid resource. Do not fiddle with the default.
</longdesc>
<shortdesc lang="en">Number of clones</shortdesc>
<content type="integer" default="2"/>
</parameter>

<parameter name="clone_node_max" required="1">
<longdesc lang="en">
Clones per node. Do not fiddle with the default.
</longdesc>
<shortdesc lang="en">Number of nodes</shortdesc>
<content type="integer" default="1"/>
</parameter>

<parameter name="master_max" required="1">
<longdesc lang="en">
Maximum number of active primaries. Do not fiddle with the default.
</longdesc>
<shortdesc lang="en">Number of primaries</shortdesc>
<content type="integer" default="1"/>
</parameter>

<parameter name="master_node_max" required="1">
<longdesc lang="en">
Maximum number of primaries per node. Do not fiddle with the default.
</longdesc>
<shortdesc lang="en">Number of primaries per node</shortdesc>
<content type="integer" default="1"/>
</parameter>
</parameters>

<actions>
<action name="start"   timeout="240" />
<action name="promote"   timeout="90" />
<action name="demote"   timeout="90" />
<action name="notify"   timeout="90" />
<action name="stop"    timeout="100" />
<action name="monitor" depth="0"  timeout="20" interval="20" start-delay="1m" role="Slave" />
<action name="monitor" depth="0"  timeout="20" interval="10" start-delay="1m" role="Master" />
<action name="meta-data"  timeout="5" />
<action name="validate-all"  timeout="30" />
</actions>
</resource-agent>
END

	exit $OCF_SUCCESS
}

do_cmd() {
	local cmd="$*"
	ocf_log debug "WiKID: Calling $cmd"
	local cmd_out=$($cmd 2>&1)
	ret=$?
	
	if [ $ret -ne 0 ]; then
		ocf_log err "WiKID: Called $cmd"
		ocf_log err "WiKID: Exit code $ret"
		ocf_log err "WiKID: Command output: $cmd_out"
	else
		ocf_log debug "WiKID: Exit code $ret"
		ocf_log debug "WiKID: Command output: $cmd_out"
	fi
	
	echo $cmd_out
	
	return $ret
}

do_wikidctl() {
	local cmd="$WIKIDCTL $*"
	do_cmd $cmd
}

wikid_init() {
	CRM_MASTER=/usr/sbin/crm_master
	
	if [ ! -d "/etc/WiKID" ]; then
		ocf_log err "WiKID not configured."
		exit $OCF_ERR_CONFIGURED
	fi

	. /etc/WiKID/setenv.sh
	WIKIDCTL=$WIKID_HOME/bin/wikidctl

	if [ -z "$WIKIDCTL" -o ! -x "$WIKIDCTL" ]; then
		ocf_log err "wikidctl not installed."
		exit $OCF_ERR_INSTALLED
	fi
	
	WIKID_ROLE=$($WIKIDCTL role 2>/dev/null)
	if [ -n "$role" ] || [ "$role" == "none" ]; then
		ocf_log err "WiKID replication not configured."
		exit $OCF_ERR_CONFIGURED
	fi

	CLONE_NO="$OCF_RESKEY_CRM_meta_clone"
	
}


#######################################################################

wikid_usage() {
	cat <<END
usage: $0 {start|stop|monitor|validate-all|promote|demote|notify|meta-data}

Expects to have a fully populated OCF RA-compliant environment set.
END
}

is_wikid_replication_enabled () {
	# $WIKID_ROLE set during wikid_init()
	if [ "$WIKID_ROLE" == "master" ] || [ "$WIKID_ROLE" == "slave"  ]; then
		return 0
	fi
	return 1
}


wikid_get_status() {
	WIKID_MESG=$(do_wikidctl status)
        WIKID_STATE=$(echo $WIKID_MESG | sed -e 's#:.*##')
        WIKID_STATUS=$(echo $WIKID_MESG | sed -e 's#.*:##')
	ocf_log debug "WiKID status: role:$WIKID_ROLE state:$WIKID_STATE status:$WIKID_STATUS"
}

wikid_start() {
	if is_wikid_replication_enabled; then
	    : OK
	else
		ocf_log debug "WiKID start: wikid replication is not enabled"
		return $OCF_ERR_GENERIC 
	fi

	wikid_get_status

	if [ "$WIKID_STATE" == "Started" ]; then
		ocf_log debug "WiKID start: already started."
		return $OCF_SUCCESS
	fi

	# Clear preference for becoming master
	do_cmd $CRM_MASTER -D
	
	# Heartbeat is trying to switch us, so let's make sure it happens in the right order
	if [ "$WIKID_ROLE" == "master" ] && [ "$OCF_RESKEY_wikid_role" == "slave" ]; then
		ocf_log debug "WiKID start: demoting master to slave..."
		do_wikidctl -y demote
	elif [ "$WIKID_ROLE" == "slave" ] && [ "$OCF_RESKEY_wikid_role" == "master" ]; then
		ocf_log debug "WiKID start: promoting slave to master ..."
		do_wikidctl -y promote
	fi

	if do_wikidctl start ; then
		ocf_log debug "WiKID start: succeeded."
		if [ "$WIKID_ROLE" = "master" ]; then
			do_cmd $CRM_MASTER -v 75
		fi
		return $OCF_SUCCESS
	else
		ocf_log err "WiKID: Failed to start up."
		if [ "$WIKID_ROLE" = "master" ]; then
			do_cmd $CRM_MASTER -v 5
		fi
		return $OCF_ERR_GENERIC
	fi
}

wikid_stop() {
	# Do not bother if wikid is not enabled
	if is_wikid_replication_enabled; then
		wikid_get_status
		
		if [ "$WIKID_STATE" == "Stopped" ]; then
			ocf_log debug "WiKID stop: already stopped."
			return $OCF_SUCCESS
		fi
		
		# TODO: this is a _force_ operation. we may need to kill higher
		# levels to be able to down wikid. figure out how...
		if do_wikidctl stop ; then
			ocf_log debug "WiKID stop: wikidctl down succeeded."
			return $OCF_SUCCESS
		else
			ocf_log err "WiKID stop: Failed with exit code: $?"
			return $OCF_ERR_GENERIC
		fi
	else
		ocf_log debug "WiKID stop: wikid replication is not enabled"
	fi

	return $OCF_SUCCESS
}

wikid_monitor() {
	# TODO: Think about how to monitor wikid and what constitutes
	# failure cases...
	# diskless etc?
	# A secondary node which is supposed to be primary?
	if is_wikid_replication_enabled; then
	    : OK
	else
	    ocf_log warn "WiKID monitor: wikid replication not configured."
	    return $OCF_NOT_RUNNING
	fi

	wikid_get_status

	if [ "$WIKID_STATE" == "Stopped" ]; then
	    ocf_log debug "WiKID monitor: not running."
	    return $OCF_NOT_RUNNING
	elif [ "$WIKID_ROLE" == "master" ]; then
	    return $OCF_RUNNING_MASTER
	elif [ "$WIKID_ROLE" == "slave" ]; then
	    return $OCF_SUCCESS
	else
	    ocf_log err "WiKID monitor: unexpected role: $WIKID_ROLE"
	fi
	
	return $OCF_ERR_GENERIC
}

wikid_promote() {
	if is_wikid_replication_enabled; then
	    : OK
	else
	    ocf_log err "wikid replication is not enabled"
	    return $OCF_ERR_GENERIC
	fi

	wikid_get_status

	if [ "x$WIKID_ROLE" = "xmaster" ]; then
		ocf_log debug "WiKID promote: already master"
		return $OCF_RUNNING_MASTER
	fi
	if [ "x$WIKID_ROLE" != "xslave" ]; then
		ocf_log debug "WiKID promote: Not slave to start with"
		return $OCF_ERR_GENERIC
	fi
	if do_wikidctl promote ; then
		ocf_log debug "WiKID promote: primary succeeded"
		return $OCF_SUCCESS
	else
		ocf_log err "WiKID promote: Failed with exit code $?."
		return $OCF_ERR_GENERIC
	fi
}

wikid_demote() {
	if is_wikid_replication_enabled; then
	    : OK
	else
	    # A stopped resource also is demoted.
	    ocf_log debug "WiKID demote: wikid replication is not enabled"
	    return $OCF_SUCCESS
	fi
	
	if [ "$WIKID_ROLE" == "slave" ]; then
		ocf_log debug "WiKID demote: already slave"
		return $OCF_SUCCESS
	fi
	if [ "$WIKID_STATUS" == "stopped" ]; then
		ocf_log debug "WiKID demote: already stopped"
		return $OCF_SUCCESS
	fi
	
	# TODO: this is a _force_ operation. we may need to kill higher
	# levels (or switch them to r/o) to be able to demote wikid.
	# figure out how...
	if do_wikidctl demote ; then
	        ocf_log debug "WiKID demote: succeeded"
		return $OCF_SUCCESS
	else
	        ocf_log err "WiKID demote: Failed with exit code $?."
		return $OCF_ERR_GENERIC
	fi
}

wikid_notify() {
	local n_type="$OCF_RESKEY_CRM_meta_notify_type"
	local n_op="$OCF_RESKEY_CRM_meta_notify_operation"
	set -- $OCF_RESKEY_CRM_meta_notify_active_resource
	local n_active="$#"
	set -- $OCF_RESKEY_CRM_meta_notify_stop_resource
	local n_stop="$#"
	set -- $OCF_RESKEY_CRM_meta_notify_start_resource
	local n_start="$#"

	ocf_log debug "WiKID notify: $n_type for $n_op - counts: active $n_active - starting $n_start - stopping $n_stop"
	
	case $n_type in
	pre)
		case $n_op in
		promote) # TODO:
			 # Resist promotion of the other side in case we
			 # are already primary - though the CRM should
			 # not even attempt that.
			;;
		esac
		;;
	post)
		case $n_op in
		start)
			#if [ "$n_active" -eq 2 ]; then
				## The other side is running, so we ought
				## to connect and wait for that.
				#wikid_start_phase_2 yes
			#else
				#wikid_start_phase_2 no
			#fi
			: what should we do here?
			;;
		# TODO: Does "fence" actually happen?
		stop|fence)
			# This MUST be a notification for the other side
			# having been stopped, because for sure we won't
			# receive one for ourselves being stopped ;-)
			# So to allow continuing with freeze_io, we need
			# to explicitly disconnect.
			#do_wikidctl disconnect 
			# TODO: If we are secondary, do we need to do
			# anything about a stopped primary in case we
			# had an outdated flag...?
			;;
		monitor)
			# TODO: We don't get notifications for failed
			# monitors yet.
			;;
		esac
		;;
	esac
	
	return $OCF_SUCCESS
}

wikid_validate_all () {
	# First, make sure the config directory exists
	local WIKIDETC=/etc/WiKID
	# First check the configuration file
	if [ -n "$WIKIDETC" ] && [ ! -d "$WIKIDETC" ]; then
	    ocf_log err "Configuration directory does not exist: $WIKIDETC"
	    return $OCF_ERR_CONFIGURED
	fi

	. $WIKIDETC/setenv.sh

	# Second, check the application directory, which is set in setenv.sh above
	if [ -n "$WIKID_HOME" ] && [ ! -d "$WIKID_HOME" ]; then
	    ocf_log err "Application directory does not exist: $WIKID_HOME"
	    return $OCF_ERR_CONFIGURED
	fi

	if [ "$OCF_RESKEY_CRM_meta_clone_max" -ne 2 ] \
	 || [ "$OCF_RESKEY_CRM_meta_clone_node_max" -ne 1 ] \
	 || [ "$OCF_RESKEY_master_node_max" -ne 1 ] \
	 || [ "$OCF_RESKEY_master_max" -ne 1 ] ; then
		ocf_log err "Clone options misconfigured."
		exit $OCF_ERR_CONFIGURED
	fi
	
	return $OCF_SUCCESS
}

(
echo "---------------------------------------------------------------"
date
echo "Args: $*"
env | grep OCF
) >> /tmp/wikid-ha.log

if [ $# -ne 1 ]; then
	echo "Incorrect parameter count."
	wikid_usage
	exit $OCF_ERR_ARGS
fi

ACTION=$1
case $ACTION in
meta-data)	meta_data
		;;
validate-all)	wikid_init
		wikid_validate_all
		;;
start|stop|monitor|promote|demote|notify)
		if ocf_is_root ; then : ; else
			ocf_log err "You must be root to perform this operation."
			exit $OCF_ERR_PERM
		fi
	
		wikid_init
		wikid_$ACTION
		exit $?
		;;
usage|help)	wikid_usage
		exit $OCF_SUCCESS
		;;
*)		wikid_usage
		exit $OCF_ERR_ARGS
		;;
esac

