#!/bin/sh
#
# Copyright: (C) 2003 International Business Machines Corporation
# Author:	Alan Robertson <alanr@unix.sh>
# License:      GNU General Public License (GPL)
# Support:      linux-ha@lists.linux-ha.org
#

#
#	OCF resource agent wrapper script for "original" heartbeat
#	resource system
#
#	This allows heartbeat to use OCF resource agents.
#
#	They are configured in /etc/ha.d/haresources like this:
#
#	OCF::resource-type::resource-instance-name
#
#	Note that resource-type must be a script in the ${OCF_AGENTS} directory
#	and that resource-instance-name must be a configuration file in
#	${HA_DIR}/conf/OCF/OCF-resource-name/
#

HA_HBCONF_DIR=@HA_HBCONF_DIR@

# Source function library.
. $HA_HBCONF_DIR/shellfuncs

# ${HA_DIR} is where things show up
# ${HA_DIR}/conf/OCF is where we find our resource settings.
#	One directory per resource type
#
# ${OCF_AGENTS} is a directory above where OCF resource agent scripts
#	are found
#
#
usage() {
	cat <<-! >&2
	usage: $0 OCF-resource-name OCF-instance-name operation-name

	OCF-resource-name is the name of an OCF-compliant resource agent
	script found under an immediate subdirectory of ${OCF_AGENTS}

	OCF-instance-name is the name of an instance of OCF-resource-name.
	It corresponds to an instance conf file named
	${HA_DIR}/conf/OCF/OCF-resource-name/OCF-instance-name

	operation-name is one of:
		start
		stop
		status
		monitor

	!
	exit 1
}

#
#	Official OCF environment variable names
#
OCF_RES_VERSION_MAJOR=1
OCF_RES_VERSION_MAJOR=0
OCF_RES_NAME=$2
export OCF_RES_VERSION_MAJOR OCF_RES_VERSION_MAJOR OCF_RES_NAME

ocf_catvars()
{
  cat $Resource_Inst_File | sed -e 's%#.*%%' -e 's%^[ 	]*%%' | grep '.'
}

ocf_varnames()
{
  ocf_catvars | grep '=' | sed 's%=.*%%'
}

ocf_setvars()
{
  . $Resource_Inst_File
  for j in `ocf_varnames`
  do
    eval export $j
  done
}

ocf_op() {
  (
    ocf_setvars
    $Resource_Script $1
  )
}

rname()
{
  echo "OCF Resource $Resource_Name::$Resource_Instance"
}

ocf_status() {
  statoutput=`OCF_STATUS_QOS=0 ocf_op status`
  rc=$?
  case $statoutput in
    "")	;;
    *)  ha_log "info: $statoutput"
  esac
  if
    [ $rc -eq 0 ]
  then
    case $statoutput in
      *OK*|*running*)	echo $statoutput;;
      *)		echo "`rname` is running"
			;;
    esac
    return 0
  else
    case $statoutput in
      *OK*|*running*)	echo "`rname` is stopped"
			;;
      *)		echo "$statoutput";;
    esac
    return $rc
  fi
}

ocf_monitor()
{
  OCF_STATUS_QOS=10 ocf_op status
}

if
  [ $# -ne 3 ]
then
  usage
fi

Resource_Name=$1
Resource_Instance=$2
Operation=$3
Resource_Inst_File="${HA_DIR}/conf/OCF/${Resource_Name}/${Resource_Instance}"
Resource_Script=`ls ${OCF_AGENTS}/*/${Resource_Name} 2>/dev/null | head -n 1`


if
  [ ! -f "$Resource_Script" -o ! -x "$Resource_Script" \
    ! -f "$Resource_Inst_File" ]
then
  usage
fi


case $Operation in
  status)	ocf_status;;
  monitor)	ocf_monitor;;
  *)		ocf_op $Operation;;
esac
