#!/bin/sh -e
#
# This script helps to find RRD group for specified host.
#
# $Header$

PATH=/bin:/usr/bin
export PATH


#-- Subroutines --------------------------------------------------------

err()
{
	local _exitval

	_exitval=$1
	shift

	echo 1>&2 "ERROR: $*"
	exit $_exitval
}

usage()
{
	echo 1>&2 "Usage: ${thiscmd} <part_of_hostname>"
	exit 1
}

get_opts()
{
	if [ $# -ne 1 ]; then
		usage
	fi

	host="$1"
}

get_groups()
{
	local _instance _root _menu _groups

	for _instance in $rrd_instances
	do
		eval _root=\${rrd_${_instance}_root}
		eval _menu=\${rrd_${_instance}_menu}

		if ! _groups=$(fetch -qo - $_menu | \
			sed -Ene "s/^.*input.*name=['\"]?h:${host}.*value=['\"]?([^'\"]+)['\"]?.*/\1/p" | \
			sort | uniq -c)
		then
			err 1 "Can't get group !"
		fi

		if [ -n "${_groups}" ]; then
			printf "===> %s\n%4s %s\n%s\n" \
				$_root NUM GROUP "${_groups}"
		fi
	done
}


#-- Variables ----------------------------------------------------------

thiscmd=$(basename $0)

rrd_instances="prod dev"

rrd_prod_root="http://searchgraph.yandex.ru/RRD/"
rrd_prod_menu="${rrd_prod_root}menu.html"

rrd_dev_root="http://terek.yandex.ru/RRD/"
rrd_dev_menu="${rrd_dev_root}menu.html"


#-- Main ---------------------------------------------------------------

get_opts $@
get_groups

