#!/bin/bash

target=`crm_node -n`

USAGE_TEXT="Usage: crm_master <command> [<options>]
Common options:
 --help 		Display this text, then exit
 --version 		Display version information, then exit
 -V, --verbose 		Specify multiple times to increase debug output
 -q, --quiet 		Print only the value (if querying)

Commands:
 -G, --query 		Query the current value of the master score
 -v, --update=VALUE	Update the value of the master score
 -D, --delete 		Delete the master score

Additional Options:
 -N, --node=NODE	Use master score on named node (instead of local node)
 -l, --lifetime=VALUE	Until when should the setting take effect
                     	(valid values: reboot, forever)
 -i, --id=VALUE		(Advanced) XML ID used to identify master score attribute"

HELP_TEXT="crm_master - Query, update, or delete a resource's promotion score

This program should normally be invoked only from inside an OCF resource agent.

$USAGE_TEXT"

exit_usage() {
	if [ $# -gt 0 ]; then
		echo "error: $@" >&2
	fi
	echo
	echo "$USAGE_TEXT"
	exit 1
}

SHORTOPTS_DEPRECATED="U:Q"
LONGOPTS_DEPRECATED="uname:,get-value,delete-attr,attr-value:,attr-id:"
SHORTOPTS="VqGv:DN:l:i:r:"
LONGOPTS="help,version,verbose,quiet,query,update:,delete,node:,lifetime:,id:,resource:"

TEMP=$(getopt -o ${SHORTOPTS}${SHORTOPTS_DEPRECATED} \
	--long ${LONGOPTS},${LONGOPTS_DEPRECATED} \
	-n crm_master -- "$@")
if [ $? -ne 0 ]; then
	exit_usage
fi

eval set -- "$TEMP" # Quotes around $TEMP are essential

while true ; do
	case "$1" in
		--help) 
			echo "$HELP_TEXT"
			exit 0
			;;
		--version)
			crm_attribute --version
			exit 0
			;;
		--verbose|-V|--quiet|-q|--query|-G|--delete|-D)
			options="$options $1"
			shift
			;;
	        -N|--node|-U|--uname)
			target="$2"
			shift
			shift
			;;
		--update|-v|--lifetime|-l|--id|-i)
			options="$options $1 $2"
			shift
			shift
			;;
		-r|--resource)
			OCF_RESOURCE_INSTANCE=$2;
			shift
			shift
			;;
		--get-value|--delete-attr|-Q) # deprecated
			options="$options $1"
			shift
			;;
		--attr-value|--attr-id) # deprecated
			options="$options $1 $2"
			shift
			shift
			;;
		--)
			shift
			break
			;;
		*)
			exit_usage "unknown option '$1'"
			;;
	esac
done

if [ -z "$OCF_RESOURCE_INSTANCE" ]; then
	echo "This program should normally only be invoked from inside an OCF resource agent."
	echo "To set a promotion score from the command line, please specify resource with -r."
	exit 1
fi

crm_attribute -N $target -n master-$OCF_RESOURCE_INSTANCE $options
