#!/usr/bin/perl -w

use strict;
use RRDs;
use IO::File;
use SNMP_Session;
use SNMP_util;
use Config::IniFiles;

my ($inicfg);

my ($cfgfile) = "/tmp/squidstats-52/etc/squidstats//config.ini";

sub read_oids($) {
	my ($fn) = @_;
	my ($f) = new IO::File;
	my (@cfg);
	$f->open($fn, O_RDONLY) || die "Couldn't read $fn: $!\n";
	while (<$f>) {
		chomp;
		s/#.*$//;
		s/[\t\s]+/ /g;
		s/[\t\s]*$//;
		next if /^$/;
	 	# print "read: '$_'\n";
		my ($type, $var) = split(/ /);
		# print "read: $type, $var\n";
		my ($n) = $var;
		$n =~ s/^cache//;
		$n =~ s/^Proto//;
		$n =~ s/\.5//;
		push @cfg, { "type" => $type, "var" => $var, "name" => $n };
	}
	return \@cfg;
}

# We create one rrd database per monitored SNMP variabl..
sub create_db {
	my (@dslist);
	my (@rralist);
	my ($step) = 300;
	my ($heartbeat) = $step * 2;

	my ($oids) = read_oids($inicfg->val("graph", "oid_file"));
	my (@a) = ( "1:576", "6:336", "12:744", "288:365", "2016:520" );
	my (@rra);
	foreach (@a) {
		push @rra, "RRA:AVERAGE:0.99:$_";
		push @rra, "RRA:MAX:0.99:$_";
		push @rra, "RRA:MIN:0.99:$_";
	}

	my (@ds);

	foreach (@$oids) {
		my ($t) = $_;
		if ($t->{"type"} eq "gauge" ) {
			push @ds, "DS:" . $t->{"name"} . ":GAUGE:" . $heartbeat . ":0:U";
		} elsif ($t->{"type"} eq "counter") {
			push @ds, "DS:" . $t->{"name"} . ":DERIVE:" . $heartbeat . ":0:U";
		} else {
			print "ERROR: unknown type " . $t->{"type"} . "\n";
			next;
		}
	}

	RRDs::create ($inicfg->val("graph", "database_file"), "--step", "300", @ds, @rra);
	print "return: " . RRDs::error . "\n" if defined RRDs::error;
	return (defined RRDs::error);
}

sub fetch {
	my ($r) = snmpMIB_to_OID($inicfg->val("squid", "mib_file"));
	if ($r <= 0) {
		print "ERROR: Couldn't read " . $inicfg->val("squid", "mib_file") . ": $!\n";
		return -1;
	}

	# build OID list
	my ($oids) = read_oids($inicfg->val("graph", "oid_file"));
	my (@vars, @names);
	foreach (@$oids) {
		push @vars, $_->{"var"};
		push @names, $_->{"name"};
	}
	my (@r);
	foreach (@vars) { print "Got: $_\n"; }
	@r = snmpget($inicfg->val("squid", "snmp_agent"), @vars);
	if (! @r) {
		print "ERROR: couldn't fetch data via SNMP\n";
		return -1;
	}
	my (@vals);
	foreach (@r) { print "READ: " . $_ . "\n"; }
	print "names: " . join(":", @names) . "\n";
	print "values: " . join(":", @r) . "\n";
	RRDs::update($inicfg->val("graph", "database_file"), "--template", join(":", @names), "N:" . join(":", @r));
	if (defined RRDs::error) {
		print "ERROR: " . RRDs::error . "\n";
		return -1;
	} else {
		print "OK\n";
		return 0;
	}
}

sub usage()
{
	print "Usage: $0 {createdb|gather}\n";
}

if (scalar @ARGV < 1) {
	usage();
	exit(127);
}

$inicfg = new Config::IniFiles( -file => "$cfgfile" ) || die "Couldn't open $cfgfile: $!\n";

if ($ARGV[0] eq "createdb") {
	create_db();
} elsif ($ARGV[0] eq "gather") {
	fetch();
} else {
	print "ERROR: missing valid command!\n";
	usage();
	exit 127;
}
exit 0;
