#!/usr/local/bin/perl

#
#	This programm starts an etherStats Collector and displays
#	the data this collector collects.
#	It should be called as:
#
#	etherstats <host> <community> <medium> <iface>
#
#
require "spook.pl";	   
require "collector.pl";
#
# handle the arguments
#
if( @ARGV != 4 )
{
	die "call as:  etherstats <host> <community> <medium> <iface>\n";
}
($iniHost , $iniComm , $iniMed , $iniIface , @rest) = @ARGV;

#
# function iniFun will be called during initialisation
# of the collector. This is the place to set all kind
# of collector specific values. In the case of etherStats, 
# this is only the ethernet-interface number etherStatsDataSource
#
sub iniFun
{
	local($connNr , $collName , $collNr) = @_;
	local($varName , $res , $iface);
	
	# the etherStat collector requires that 	
	# dataSource should be set to the active device number
	$varName = $collName . "DataSource\[$collNr\]";
	#
	# yes we know, very ugly
	$iface = "1.3.6.1.2.1.2.2.1.1." . $iniIface;
	$res = &snmp_set($connNr,"$varName=$iface");
	if($res != $iface)
	{
		return 0;
	}
	return 1;
}	   

# create the SPOOK connection
&snmp_open(1) || die "cant open\n";
&snmp_host(1,$iniHost);
&snmp_medium(1,$iniMed);
&snmp_connect(1) || die "could't connect to ($iniHost,$iniMed)";
&snmp_community(1,$iniComm);


# create the etherStats collector with the correct inFun
$connNr = &create_new_collector(1,"etherStats","eikel",main'iniFun) || die "failed creating\n";
print "created etherStats collector $connNr\n";

#prepare the signal handler
sub sigHandler
{
	local($sig) = @_;
	print("\nTerminating etherstats collector and exiting\n");
	# remove the etherStats collector
	&remove_collector(1,"etherStats",$connNr,"eikel") || die "failed removing\n";
	
	# close the Spook connection
	&snmp_disconnect(1);
	&snmp_close(1);
	exit;
}
$SIG{'INT'}  = 'sigHandler';
$SIG{'QUIT'} = 'sigHandler';

#prepare a list of MIB variables that will be collected on one SNMP message
@statsList = (
	"etherStatsOctets[$connNr]",
	"etherStatsPkts[$connNr]",
	"etherStatsBroadcastPkts[$connNr]",
	"etherStatsMulticastPkts[$connNr]",
	"etherStatsPkts64Octets[$connNr]",
	"etherStatsPkts65to127Octets[$connNr]",
	"etherStatsPkts128to255Octets[$connNr]",
	"etherStatsPkts256to511Octets[$connNr]",
	"etherStatsPkts512to1023Octets[$connNr]",
	"etherStatsPkts1024to1518Octets[$connNr]"
);
while (1)
{
	# Get and Display the results
	
	printf("\n%07s%07s%07s%07s%07s%07s%07s%07s%07s%07s\n",
			"Octets",
			"Pkts",
			"BrdCst",
			"MltCst",
			"==64",
			"65-127",
			"128-255",
			"256-511",
			"512-1023",
			"1K-1518"
			);
	for($i=0;$i<22;$i++)
	{
		@eikel = &snmp_get(1,@statsList);
		foreach $var (@eikel)
		{
			printf("%7d",$var);
		}
		printf("\n");
		sleep(1);
	}
}

# shouldn't come here
	      
# remove the etherStats collector
&remove_collector(1,"etherStats",$connNr,"eikel") || die "failed removing\n";

# close the Spook connection
&snmp_disconnect(1);
&snmp_close(1);

