#!/bin/sh
echo "Content-type: image/png"
echo

#if test ! "$1"
#then
#        echo "$0: We need a hostname!"
#        echo "Usage: $0 hostname"
#        exit 1
#fi

DYNAMIC_HOSTNAME="$1"
BBRRDS="/usr/local/bb/rrd"
BBHOME="/usr/local/bb"

#set -x

# bbnet-graph.sh

# this script will build tcp PNG's
# using $RRDTOOL graph with RRD's built via
# the BB ext script larrd.sh

if test ! "$BBHOME"
then
        echo "$0: BBHOME is not set"
        exit 1
fi

if test ! -d "$BBHOME"
then
        echo "$0: BBHOME is invalid"
        exit 1
fi

# source the conf
. $BBHOME/etc/bbdef.sh
. $BBHOME/ext/larrd/larrd.conf

# get current date
DATE=`date`
# initialize color counter
c=0

# get to work
cd $BBRRDS

# figure out which hosts have tcp info
#for HOST in `ls *.tcp* | $SED 's/\.tcp.*.rrd//' | uniq ` 
for HOST in `ls ${DYNAMIC_HOSTNAME}.tcp* | $SED 's/\.tcp.*.rrd//' | uniq ` 
do
	# variable reset for each host
	DEFS=""
	LINES=""
	c=0
	p=0
	
	# get list of parition RRD's and build RRD DEF's and LINES
	for rrd in `ls $HOST.tcp.*.rrd` 
	do
		# gosh i miss perl
		PART=`echo $rrd | $SED 's/^.*tcp\.//' | $SED 's/\.rrd//' `
		# the PARTRRD is arbitrary, so trying to use
		# partition name was senseless cause rrdtool
		# is very sensitive to non-alphanumeric characters
		PARTRRD=$p
		p=`expr $p + 1`

		# the comment should try and look nice
		PARTCOMM=`echo $PART | $SED 's/,/\\//g' `
		
		# for rrd's with : we need to clean up
		# <Jeff@mdli.com>
		rrd=`echo $rrd | $SED 's/\:/\\\:/g' `
		PARTCOMM=`echo $PARTCOMM | $SED 's/\:/\\\:/g' `
				
		# build the DEFs var
		DEFS="$DEFS DEF:$PARTRRD=$rrd:sec:AVERAGE"

		# get the color to use
		# this is soooooo bad but it was the best 
		# i could come up with
		i=0
		for col in $COLORS
		do
			if [ $c -eq $i ]
			then
				COL=$col
			fi
			i=`expr $i + 1`
		done
		if [ $c -eq 12 ]
		then
			c=0
		else
			c=`expr $c + 1`
		fi
				
		# build the LINES var
		LINES="$LINES LINE2:$PARTRRD#$COL:$PARTCOMM" 
	done

	# now start building graphs
	# define the graphs for each time period
	HOURLY=$GRAPHS/$HOST.tcp.hourly.png
	DAILY=$GRAPHS/$HOST.tcp.daily.png
	WEEKLY=$GRAPHS/$HOST.tcp.weekly.png
	MONTHLY=$GRAPHS/$HOST.tcp.monthly.png

	# make the hourly graph
	$RRDTOOL graph - -s e-48h --title="$HOST tcp connect \
	time last 48 Hours" \
	-w 576 -a PNG -z -v "Seconds"  $DEFS $LINES \
	COMMENT:"\s" COMMENT:"$DATE\r"
	
done
