#!/bin/sh 

_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-heartbeat" "$1"
}

#turn off auto expansion
set -f

. /usr/share/alterator/build/backend3.sh

DEBUG=1

debug()
{
    if [ "$DEBUG" = "1" ]; then
	echo -e "$@" >> /root/debug
    fi
}

resource_exists()
{
    new_resource="$1"
    /usr/lib/alterator-heartbeat/list-resources.sh 2> /dev/null | while read resource def; do
	if [ "$new_resource" = "$resource" ]; then
	    echo "exists"
	fi
    done
}

on_message()
{
	case "$in_action" in
		#information for renderer
		template)
			echo '('
			echo ' template "form"'
			echo ' help "heartbeat.html"'
			if [ "$in__objects" = "/" ]; then
				/usr/lib/alterator-heartbeat/wait-for-cluster-ready.sh || \
				in_orig_action=""
				if [ "$in_orig_action" = "add" ]; then
				    if [ x$(resource_exists "$in_resource_name") = x"exists" ]; then
					echo ' url "heartbeat.html"'
				    else
					echo "$in_resource_name" | egrep -qs '^[a-zA-Z0-9_-]+$' && \
					    printf 'redirect "/heartbeat/%s/%s"' "$in_resource_type" "$in_resource_name" || \
					    echo ' url "heartbeat.html"'
				    fi
				else
				    echo ' url "heartbeat.html"'
				fi
			else
			    local resource_type="${in__objects%/*}"
			    resource_type="${resource_type##*/}"
			    case "$resource_type" in
				IPaddr)
				    echo ' url "heartbeat-resource-ipaddr.html"'
				    echo ' redirect "/heartbeat"'
				    ;;
				Openldap)
				    echo ' url "heartbeat-resource-openldap.html"'
				    echo ' redirect "/heartbeat"'
				    ;;
				*)
				    echo '#f'
				    ;;
			    esac
			fi
			echo ')'
			;;
		info)
			echo '('
			printf ' title "%s"' "`_ "Heartbeat settings"`" #"
			printf ' description "%s"' "`_ "Heartbeat settings"`"
			printf ' group "%s"' "`_ "Servers"`"
			echo ')'
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
