#!/usr/bin/bash
#
# HA cluster manager script to unregister resources from a node.
# Depending on the case, it will be executed on:
# - cluster node crash: master node
# - broken resource relocation: master node
# - active resource relocation: source node

# Use the following environment variables:
# EVENT - name of the cluster event
# RESOURCE - id of resource 
# RESOURCE_PATH - path to resource 
# SRC_NODE - address of source node
# DST_NODE - address of target node
#
# Copyright (c) 2013-2017, Parallels International GmbH
#
# Our contact details: Parallels International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

. /usr/share/shaman/functions

verify_caller

if [ -z "$RESOURCE" ]; then
	echo "RESOURCE environment variable undefined" 1>&2
	exit 1
fi

HANDLER_NAME=`basename $0`
HANDLER_PATH="/usr/share/shaman"
HANDLER_LIST=`find "${HANDLER_PATH}" -mindepth 1 -maxdepth 1 -type d -printf "%f " | sort -r`

# try to unregister resource from old owner
# to avoid restart resources from previous node
for HANDLER in ${HANDLER_LIST}; do
	RESOURCE_ID=${RESOURCE#$HANDLER}
	if [ "X$RESOURCE_ID" != "X$RESOURCE" ]; then
		SCRIPT=$HANDLER_PATH/$HANDLER/${HANDLER_NAME}.sh
		if [ -e "$SCRIPT" ]; then
			CMD="RESOURCE_PATH=\"${RESOURCE_PATH}\" SRC_NODE=${SRC_NODE} DST_NODE=${DST_NODE} $SCRIPT"
			eval $CMD
			RET=$?
			if [ $RET -ne 0 ]; then
				echo "'$CMD' failed with code $RET" 1>&2
				exit $RET
			fi
		fi
		exit 0
	fi
done
echo "Resource handler not found" 1>&2
exit 1
