#! /usr/bin/perl -w

# Structure de la table utilisée :

# CREATE TABLE `SNMPDATA`.`results` (
# `id_result` BIGINT NOT NULL AUTO_INCREMENT ,
# `date_result` DATETIME NOT NULL ,
# `value` VARCHAR( 255 ) NOT NULL ,
# PRIMARY KEY ( `id_result` )
# ) TYPE = MYISAM 

use strict;

use Date::Format;
use Net::SNMP;
use DBI;

# Database information
my $db="SNMPDATA";			# Database name
my $host="localhost";		# Database host
my $port=3306;					# Database port
my $userid="root";			# Database user
my $passwd="mysql";			# Database password
my $connectionInfo="DBI:mysql:database=$db;$host:$port";   # Database connection string
my $dbh;                                                   # Database handle

print "Creating SNMP Session ";
my ($session, $error) = Net::SNMP->session(
   -hostname  => shift || 'localhost',
   -community => shift || 'public',
   -port      => shift || 161 
);

if (!defined($session)) {
   printf("ERROR: %s.\n", $error);
   exit 1;
}
print "OK\n";

my $sysUpTime = '1.3.6.1.2.1.1.3.0';

print "Getting sysUpTime ";
my $result = $session->get_request(
   -varbindlist => [$sysUpTime]
);

if (!defined($result)) {
   printf("ERROR: %s.\n", $session->error);
   $session->close;
   exit 1;
}
else {
	print "OK\n";
	print "Connecting to db : $db\n";
	unless ( $dbh = DBI->connect($connectionInfo,$userid,$passwd) ) {
	        print $DBI::errstr . "\n";
	        exit 2;
	}
	print "Connected to $db.\n";

	my $uptimeValue = $result->{$sysUpTime};
	my $query = "INSERT INTO results (date_result,value) VALUES ('" . time2str("%Y-%d-%m %H:%M:%S",time) . "','" . $uptimeValue . "')";
	print "Insertion : $query ";
	my $sth = $dbh->prepare($query);
  if ($sth->execute) {
      print "OK\n";
  }
  else {
      print "Failed !\n";
  }
	$session->close;
	$dbh->disconnect();
}
exit 0;
