#!/bin/bash
#

#testing
OCF_ROOT="/usr/lib/ocf"

: ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat}
. ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs

NAME="$(basename $0)"
unset ISBOOT
if [ "${NAME:0:1}" = "S" -o "${NAME:0:1}" = "K" ]; then
    NAME="${NAME:3}"
    ISBOOT="1"
fi

SU="/bin/su -s /bin/bash"

SUBSYS="/var/lock/subsys/${NAME}"

# Get the tomcat config (use this for environment specific settings)
TOMCAT_CFG="/etc/tomcat6/tomcat6.conf"
if [ -r "$TOMCAT_CFG" ]; then
    . $TOMCAT_CFG
fi

# Get instance specific config file
if [ -r "/etc/sysconfig/${NAME}" ]; then
    . /etc/sysconfig/${NAME}
fi

# Define which connector port to use
CONNECTOR_PORT="${CONNECTOR_PORT:-8080}"

#score dla master
MASTER_SCORE=1000

#score dla slave
SLAVE_SCORE=100

# Path to the tomcat launch script
TOMCAT_SCRIPT="/usr/sbin/tomcat6"

# Tomcat program name
TOMCAT_PROG="${NAME}"
        
# Define the tomcat username
TOMCAT_USER="${TOMCAT_USER:-tomcat}"

# Define the tomcat log file
TOMCAT_LOG="${TOMCAT_LOG:-/var/log/tomcat6/${NAME}-initd.log}"

function checkpidfile()
{
	ocf_log info "$FUNCNAME issued"
	if [ -f "$CATALINA_PID" ]; then
		read kpid < $CATALINA_PID
		if [ -d "/proc/${kpid}" ]; then
			ps -u ${TOMCAT_USER} -f -p ${kpid} | grep -q '\-Denable\.master=true'
			RETURNCODE="$?"
			if [ "$RETURNCODE" -eq "0" ]; then
				return 0
			fi
			ps -u ${TOMCAT_USER} -f -p ${kpid} | grep -q '\-Denable\.slave=true'
			RETURNCODE="$?"
			if [ "$RETURNCODE" -eq "0" ]; then
				return 1 
			fi
		else
			ocf_log info "${FUNCNAME}: rm -f $CATALINA_PID"
			rm -f "$CATALINA_PID" 2>&1		
			if [ -f $SUBSYS ]; then
				ocf_log info "${FUNCNAME}: rm -f $SUBSYS"
				rm -f "$SUBSYS" 2>&1
				return 2
			fi
			return 3

		fi
	elif [ -f $SUBSYS ]; then
		ocf_log info "${FUNCNAME}: rm -f $SUBSYS"
		rm -f "$SUBSYS" 2>&1
		return 4
	else
		return 5
	fi
}

function cfg_make_master()
{
	ocf_log info "$FUNCNAME issued"
	sed -i -e 's/[[:blank:]]\+-Denable.slave=[a-z]\+//' -e 's/[[:blank:]]\+-Denable.master=[a-z]\+//' -e 's/\(JAVA_OPTS=".*\)\"/\1 -Denable.master=true\"/' $TOMCAT_CFG
}

function cfg_make_slave()
{
	ocf_log info "$FUNCNAME issued"
	sed -i -e 's/[[:blank:]]\+-Denable.slave=[a-z]\+//' -e 's/[[:blank:]]\+-Denable.master=[a-z]\+//' -e 's/\(JAVA_OPTS=".*\)\"/\1 -Denable.slave=true\"/' $TOMCAT_CFG
}

function demote()
{
	rc=$OCF_ERR_GENERIC
	ocf_log info "$FUNCNAME issued"
	monitor
	RETURNCODE="$?"
        case "$RETURNCODE" in
		"$OCF_SUCCESS")
			ocf_log info "${FUNCNAME}: process running as a slave already"
			rc=$OCF_SUCCESS
			;;
        	"$OCF_RUNNING_MASTER")
			cfg_make_slave
			stop
			start
			unset RETURNCODE
			while [ "$RETURNCODE" != "$OCF_SUCCESS" ] ;do
				ocf_log info "${FUNCNAME}: process has not started as a slave yet, waiting"
				sleep 1
				monitor
				RETURNCODE="$?"
			done
			rc=$OCF_SUCCESS
			;;
		"$OCF_NOT_RUNNING")
			ocf_log error "${FUNCNAME}: process is not running and cannot be demoted"
                        exit $OCF_ERR_GENERIC
			;;
		"*")
			ocf_log error "${FUNCNAME}: something unexpected happened"
			exit $OCF_ERR_GENERIC
			;;
	esac
	return $rc
}

function meta-data() {
	cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="tomcat6">
<version>0.9</version>

<longdesc lang="en">
This resource agent manages a Tomcat6 Solr service as a master/slave
resource. Solr service served is configured with replication: for
details please see http://wiki.apache.org/solr/SolrReplication
</longdesc>

<shortdesc lang="en">Manages a tomcat6 replicated (master/slave) solr resource</shortdesc>

<parameters>
</parameters>

<actions>
<action name="start"   timeout="60" />
<action name="promote"   timeout="60" />
<action name="demote"   timeout="60" />
<action name="notify"   timeout="60" />
<action name="stop"    timeout="60" />
<action name="monitor" timeout="60" interval="30" role="Slave" />
<action name="monitor" timeout="60" interval="31" role="Master" />
<action name="meta-data"  timeout="60" />
<action name="validate-all"  timeout="60" />
</actions>
</resource-agent>
END
	exit $OCF_SUCCESS
}

function meta_expect()
{
	local what=$1 whatvar=OCF_RESKEY_CRM_meta_${1//-/_} op=$2 expect=$3
	local val=${!whatvar}
        if [[ -n $val ]]; then
                [ $val $op $expect ] && return
        fi
	ocf_log err "meta parameter misconfigured, expected $what $op $expect, but found ${val:-unset}."
	exit $OCF_ERR_CONFIGURED
}

function monitor()
{
	ocf_log info "$FUNCNAME issued"	
	rc=$OCF_ERR_GENERIC	
	checkpidfile 
	RETURNCODE="$?"
	case "$RETURNCODE" in
	"0")
		ocf_log info "${FUNCNAME}: process is running as a master"
		ocf_log info "${FUNCNAME}: crm_master -l reboot -v $MASTER_SCORE"
                crm_master -l reboot -v $MASTER_SCORE
                rc=$OCF_RUNNING_MASTER
		;;
	"1")
		ocf_log info "${FUNCNAME}: process is running as a slave"
                ocf_log info "${FUNCNAME}: crm_master -l reboot -v $SLAVE_SCORE"
                crm_master -l reboot -v $MASTER_SCORE
		rc=$OCF_SUCCESS
		;;
	"2")
		ocf_log error "pid file and subsys file exist and the process is not running"
                ocf_log info "${FUNCNAME}: crm_master -l reboot -D"
                crm_master -l reboot -D
		rc=$OCF_ERR_GENERIC
		;;
	"3")
		ocf_log error "pid file exists and the process is not running"
                ocf_log info "${FUNCNAME}: crm_master -l reboot -D"
                crm_master -l reboot -D
		rc=$OCF_ERR_GENERIC
		;;
	"4")	
		ocf_log error "subsys file exists and the process is not running"
                ocf_log info "${FUNCNAME}: crm_master -l reboot -D"
                crm_master -l reboot -D
		rc=$OCF_ERR_GENERIC
		;;
	"5")
		ocf_log warning "process is not running"
                ocf_log info "${FUNCNAME}: crm_master -l reboot -D"
                crm_master -l reboot -D
                rc=$OCF_NOT_RUNNING
		;;
	esac
	return $rc
}

function notify()
{
	#currently there is no need for notifications	
	ocf_log info "notify invoked OCF_RESKEY_CRM_meta_notify_type: ${OCF_RESKEY_CRM_meta_notify_type}, OCF_RESKEY_CRM_meta_notify_operation=${OCF_RESKEY_CRM_meta_notify_operation}" 
	return $OCF_SUCCESS
}

function parseOptions() {
	ocf_log info "$FUNCNAME issued"
    options=""
    options="$options $(
                 awk '!/^#/ && !/^$/ { ORS=" "; print "export ", $0, ";" }' \
                 $TOMCAT_CFG
             )"
    if [ -r "/etc/sysconfig/${NAME}" ]; then
        options="$options $(
                     awk '!/^#/ && !/^$/ { ORS=" "; 
                                           print "export ", $0, ";" }' \
                     /etc/sysconfig/${NAME}
                 )"
    fi
    TOMCAT_SCRIPT="$options ${TOMCAT_SCRIPT}"
}

function promote()
{
	rc=$OCF_ERR_GENERIC
	ocf_log info "$FUNCNAME issued"
	monitor
	RETURNCODE="$?"
        case "$RETURNCODE" in
		"$OCF_RUNNING_MASTER")
			ocf_log info "${FUNCNAME}: process running as a master already"
			rc=$OCF_SUCCESS
			;;
        	"$OCF_SUCCESS")
			cfg_make_master
			stop
			start
			unset RETURNCODE
			while [ "$RETURNCODE" != "$OCF_RUNNING_MASTER" ] ;do
				ocf_log info "${FUNCNAME}: process has not started as a master yet, waiting"
				sleep 1
				monitor
				RETURNCODE="$?"
			done
			rc=$OCF_SUCCESS
			;;
		"$OCF_NOT_RUNNING")
			ocf_log error "${FUNCNAME}: process is not running and cannot be promoted"
                        exit $OCF_ERR_GENERIC
			;;
		"*")
			ocf_log error "${FUNCNAME}: something unexpected happened"
			exit $OCF_ERR_GENERIC
			;;
	esac
	return $rc
}

function start() {
	rc=$OCF_ERR_GENERIC
	ocf_log info "$FUNCNAME issued"
	monitor
	RETURNCODE="$?"
        case "$RETURNCODE" in
        	"$OCF_RUNNING_MASTER")
			ocf_log info "${FUNCNAME}: process running as a master already"
			rc=$OCF_SUCCESS
			;;
		"$OCF_SUCCESS")
			ocf_log info "${FUNCNAME}: process running as a slave already"
			rc=$OCF_SUCCESS
			;;
		"$OCF_NOT_RUNNING")
			ocf_log info "${FUNCNAME}: touch $CATALINA_PID"
			touch $CATALINA_PID 2>&1
			RETURNCODE="$?"
			if [ "$RETURNCODE" -eq 0 ]; then
				ocf_log info "${FUNCNAME}: chown ${TOMCAT_USER}:${TOMCAT_USER} $CATALINA_PID"
				chown ${TOMCAT_USER}:${TOMCAT_USER} $CATALINA_PID
			else
				ocf_log error "${FUNCNAME}: touch $CATALINA_PID failed"
				exit $OCF_ERR_GENERIC
			fi
			ocf_log info "${FUNCNAME}: touch $TOMCAT_LOG"
			touch $TOMCAT_LOG 2>&1
			RETURNCODE="$?"
			if [ "$RETURNCODE" -eq 0 ]; then
				ocf_log info "${FUNCNAME}: chown ${TOMCAT_USER}:${TOMCAT_USER} $TOMCAT_LOG"
				chown ${TOMCAT_USER}:${TOMCAT_USER} $TOMCAT_LOG
			else
				ocf_log error "${FUNCNAME}: touch $TOMCAT_LOG failed"
				exit $OCF_ERR_GENERIC
			fi
			parseOptions
			if [ "$SECURITY_MANAGER" = "true" ]; then
				ocf_log info "${FUNCNAME}: $SU - $TOMCAT_USER -c ${TOMCAT_SCRIPT} start-security"
				$SU - $TOMCAT_USER -c "${TOMCAT_SCRIPT} start-security" >> ${TOMCAT_LOG} 2>&1
				RETURNCODE="$?"
			else
				ocf_log info "${FUNCNAME}: $SU - $TOMCAT_USER -c ${TOMCAT_SCRIPT} start"
				$SU - $TOMCAT_USER -c "${TOMCAT_SCRIPT} start" >> ${TOMCAT_LOG} 2>&1
				RETURNCODE="$?"
			fi
			if [ "$RETURNCODE" -eq 0 ]; then
				ocf_log info "${FUNCNAME}: touch $SUBSYS"
				touch $SUBSYS
				unset RETURNCODE
				while [[ "$RETURNCODE" != "$OCF_SUCCESS" && "$RETURNCODE" != "$OCF_RUNNING_MASTER" ]] ;do
					ocf_log info "${FUNCNAME}: resource has not started yet, waiting"
					sleep 1
					monitor
					RETURNCODE="$?"
				done
				#wait for tomcat to start on ports 8005 8009 8080
				ocf_log info "${FUNCNAME}: sleep 10"
				ocf_log info "${FUNCNAME}: process has started properly"
				sleep 10
				rc=$OCF_SUCCESS
			else
				ocf_log error "${FUNCNAME}: process has not started properly"
				exit $OCF_ERR_GENERIC
			fi
			;;
		"*")
			ocf_log error "${FUNCNAME}: something unexpected happened"
			exit $OCF_ERR_GENERIC
			;;
	esac
	return $rc
}

function stop() {
	rc=$OCF_ERR_GENERIC
	ocf_log info "$FUNCNAME issued"
	monitor
	RETURNCODE="$?"
        case "$RETURNCODE" in
        	"${OCF_RUNNING_MASTER}"|"${OCF_SUCCESS}")
			parseOptions
			ocf_log info "${FUNCNAME}: $SU - $TOMCAT_USER -c ${TOMCAT_SCRIPT} stop"
			$SU - $TOMCAT_USER -c "${TOMCAT_SCRIPT} stop" >> ${TOMCAT_LOG} 2>&1
			RETURNCODE="$?"
			if [ "$RETURNCODE" -eq "0" ]; then	
				count="0"
				unset RETURNCODE
				while [ "$RETURNCODE" != "$OCF_NOT_RUNNING" ] ;do
					ocf_log info "${FUNCNAME}: resource has not stopped yet, waiting"
					sleep 1
					monitor
					RETURNCODE="$?"
				done
			else
				ocf_log error "${FUNCNAME}: process has not stopped properly"
                                exit $OCF_ERR_GENERIC	
			fi
			ocf_log info "${FUNCNAME}: rm -f $SUBSYS $CATALINA_PID"
			rm -f "$SUBSYS" "$CATALINA_PID" 2>&1
			ocf_log info "${FUNCNAME}: process has stopped properly"
			rc=$OCF_SUCCESS
			;;
		"$OCF_NOT_RUNNING")
			ocf_log info "${FUNCNAME}: process not running already"
			rc=$OCF_SUCCESS
			;;
		"*")
			ocf_log error "${FUNCNAME}: something unexpected happened"
			exit $OCF_ERR_GENERIC
			;;
	esac	
	return $rc
}

function validate-all()
{
	rc=$OCF_SUCCESS
	ocf_log info "$FUNCNAME issued"
	ocf_log info "${FUNCNAME}: check_binary $TOMCAT_SCRIPT issued"
	check_binary "$TOMCAT_SCRIPT"
	if ! [ -r "$TOMCAT_CFG" ]; then
		ocf_log err "${FUNCNAME}: $TOMCAT_CFG does not exist"
		rc=$OCF_ERR_INSTALLED
	fi
	meta_expect master-node-max = 1
	meta_expect master-max = 1
	meta_expect clone-node-max = 1
	meta_expect clone-max = 2
	return $rc
}

# See how we were called.
case "$1" in
	demote)
		demote
		;;
	meta-data)
		meta-data
		;;
	monitor)
		monitor
		;;
	notify)
		notify
		;;
	promote)
		promote
		;;
	start)
		cfg_make_slave
		start
		;;
	stop)
		stop
		;;
	validate-all)
		validate-all
		;;
	*)
	exit $OCF_ERR_UNIMPLEMENTED
	;;
esac
