#!/bin/bash
# -*- bash -*-

: << =cut

=head1 NAME

ipvs_conn -Indicate the number of active servers in ipvs

=head1 CONFIGURATION

[ipvs_*]
user root
env.ips IP1 IP2

=head1 AUTHOR

Ricardo Fraile <rfrail3@yahoo.es>

=head1 LICENSE

GPLv2

=head1 MAGICK MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

. $MUNIN_LIBDIR/plugins/plugin.sh


IPLIST=$ips


if [ "$1" = "autoconf" ]; then
        echo yes 
        exit 0
fi

if [ "$1" = "config" ]; then

        echo 'graph_title Ipvs Active Servers'
        echo 'graph_args --base 1000 -l 0 '
        echo 'graph_vlabel Servers'
        echo 'graph_scale no'
        echo 'graph_category loadbalancer'
        echo 'graph_info Indicate the number of active servers in Ipvs.'

	for IP in $IPLIST; do
		NM=`echo $IP | md5sum | cut -d - -f1 | sed 's/ //g' | cut -b 5-9`
	        echo "a$NM.label $IP Active"
        	echo "a$NM.type GAUGE"
	        echo "a$NM.min 0"
	done

        exit 0
fi



# Get line number of match listen ip
function get_ip {
# Read the output
ipvsadm -l -n | nl | while read line; do
	# If match the ip, print the line number	
	if ( echo $line | grep -e $IP > /dev/null ); then
		MAT=`echo $line | cut -d " " -f 1`
		echo $MAT
	fi
done
}


for IP in $IPLIST; do

	COUNT="0"
	ACTCONCNT="0"
	INACTCONCNT="0"
	F1=`mktemp`
	MATCH=`get_ip`
	ipvsadm -l -n | nl > $F1

	# Parse lines
	while read line; do
	
		# Get line numbers
		N=`echo $line | cut -d " " -f 1`

		# If line number match the line number of the match listen ip, print the line...
		if [ "$N" -gt "$MATCH" ]; then
			# ... except if the line contain TCP or UDP word (this start an other listen)
			if ( echo $line | grep -e TCP -e UDP > /dev/null ); then
				break
			fi
		
			COUNT=`expr $COUNT + 1`
		fi
	done < $F1


	# Print values
	NM=`echo $IP | md5sum | cut -d - -f1 | sed 's/ //g' | cut -b 5-9`
	echo a$NM.value $COUNT

	# Remove temp file
	rm -f $F1
done
