#!/usr/bin/perl 
$|=1;

sub check_ip {
	$OID_ifTable = '1.3.6.1.2.1.4.20.1.1';
	my $comunity = "esseweb";

	%tabella;

	$risultato = "result";

	my $fw_query = "SELECT id, nome FROM firewall WHERE attivo = 1";
	my $fw_sts = $dbmysql->prepare($fw_query);
	$fw_sts->execute ();

	while (my $fw_dato = $fw_sts->fetchrow_hashref) {
        	my $fw_id = $$fw_dato{'id'};
        	my $fw_nome = $$fw_dato{'nome'};

		$nomeres  = $risultato.$fw_id;

		my ($sessione, $errore) = Net::SNMP->session(
			-hostname    	=> shift || $fw_nome,
			-community   	=> shift || $comunity,
			-nonblocking 	=> 1,
			-translate   	=> [-octetstring => 0],
			-version     	=> 'snmpv2c',
		);

		if (!defined $sessione) {
			printf "ERROR: %s.\n", $errore;
			return 0;
		}

		my $nomehash = "temphash$fw_id";
		%$nomehash;

		$$nomeres = $sessione->get_bulk_request(
			-varbindlist    => [ $OID_ifTable ],
			-callback       => [ \&table_callback, \%$nomehash ],
			-maxrepetitions => 10,
		);

		if (!defined $$nomeres) {
			printf "ERROR: %s \n", $sessione->error();
			$sessione->close();
			return 0;
		}

		snmp_dispatcher();
		$sessione->close();
		$tabella{$fw_id} = \%$nomehash;
		my %hasttmp = \%$nomehash;
	}

	my $ip_query = "SELECT id, ip, idfirewall, attuale, errore FROM indirizzi WHERE attivo = 1 AND vf = 0";
	my $ip_sts = $dbmysql->prepare($ip_query);
	$ip_sts->execute ();

	my @query;
	my @oggetti;
	my @testi;

	while (my $ip_dato = $ip_sts->fetchrow_hashref) {
	        my $ip_id = $$ip_dato{'id'};
	        my $ip_ip = $$ip_dato{'ip'};
	        my $ip_idfirewall = $$ip_dato{'idfirewall'};
	        my $ip_attuale = $$ip_dato{'attuale'};
	        my $ip_errore = $$ip_dato{'errore'};

		my @listafw;
		while (($fwid, %tabellaip) = each(%tabella)){
			my $oid = "1.3.6.1.2.1.4.20.1.1.$ip_ip";
			if (defined $tabella{$fwid}{$oid} ) {
				push @listafw, $fwid;
			}
		}

		if (scalar(@listafw) == 1) {
			if ($listafw[0] != $ip_attuale) {
				#print "L'IP $ip_ip e' migrato dal FW $ip_attuale al FW $listafw[0]\n";
				if ($listafw[0] != $ip_idfirewall) {
					push @query, "UPDATE indirizzi SET attuale = ".$listafw[0].", errore=1  WHERE id = $ip_id";
					$testo = "L\\'IP $ip_ip non e\\' sul FW corretto ed e\\' migrato sul FW ".$listafw[0];
				} else {
					push @query, "UPDATE indirizzi SET attuale = ".$listafw[0].", errore=0  WHERE id = $ip_id";
					$testo = "L\\'IP $ip_ip e\\' migrato sul FW corretto ".$listafw[0];
				}
				push @oggetti, "Firewall Warning"; push @testi, $testo;
				push @query, "INSERT INTO log_server (fw, data, idazione, stato, testo) VALUES (".$listafw[0].", NOW(), 0, 1, '$testo')";
			}
		} elsif ((scalar(@listafw) > 1) && ($ip_errore < 2)) {
			push @query, "UPDATE indirizzi SET attuale=0, errore=2 WHERE id = $ip_id";
			push @query, "INSERT INTO log_server (fw, data, idazione, stato, testo) VALUES (0, NOW(), 0, 2, 'L\\'IP $ip_ip e\\' presente su piu\\' firewall')";
			push @oggetti, "Firewall Error"; push @testi, "L'IP $ip_ip e' presente su piu' firewall";
		} elsif ((scalar(@listafw) == 0) && ($ip_errore < 2)) {
			push @query, "UPDATE indirizzi SET attuale=0, errore=2 WHERE id = $ip_id";
			push @query, "INSERT INTO log_server (fw, data, idazione, stato, testo) VALUES (0, NOW(), 0, 2, 'L\\'IP $ip_ip non e\\' presente su nessun firewall')";
			push @oggetti, "Firewall Error"; push @testi, "L'IP $ip_ip non e' presente su nessun firewall";
		}
	}

	while (my $invia = pop @query) {
		#print "$invia\n";
		my $ip_sts = $dbmysql->prepare($invia);
		$ip_sts->execute ();
	}

	while (my $subject = pop @oggetti) {
		my $body = pop @testi;
		#print "$subject -- $body\n";
		invio ($subject, $body);
	}
}

sub table_callback {
	my ($session, $table) = @_;
	my $list = $session->var_bind_list();

	if (!defined $list) {
		printf "ERROR: %s\n", $session->error();
		return;
	}

	my @names = $session->var_bind_names();
	my $next  = undef;

	while (@names) {
		$next = shift @names;
		if (!oid_base_match($OID_ifTable, $next)) {
			return; # Table is done.
 		}
		$table->{$next} = $list->{$next};
	}

	my $result = $session->get_bulk_request(
		-varbindlist    => [ $next ],
		-maxrepetitions => 10,
	);

	if (!defined $result) {
		printf "ERROR: %s.\n", $session->error();
	}

	return;
}

sub invio {
	my ($oggetto, $testo) = @_;

	my $mittente = 'firewall@esseweb.eu';
	my @destinatario;
	push @destinatario, 'cmaffioletti@esseweb.eu';
	push @destinatario, 'fmeini@esseweb.eu';

	my $sasl = Authen::SASL->new(
		mechanism => 'CRAM-MD5 PLAIN ANONYMOUS',
		callback => {
			pass => 'l30nard0',
			user => 'cmaffio@bmm.it',
		}
	);


	my $smtp;
	if (not $smtp = Net::SMTP::SSL->new (
		'smtp.mi.esseweb.intra',
		Port => 465,
		Debug => 0)) 
	{ 
		die "Could not connect to server\n"; 
	}

	$smtp->auth($sasl) || die "Authentication failed!\n";

	$smtp->mail($mittente . "\n");
	my $to = "";
	foreach my $recp (@destinatario) {
		$smtp->to($recp . "\n");
		$to .= "$recp, ";
	}

	$smtp->data();
	$smtp->datasend("From: " . $mittente . "\n");
	$smtp->datasend("To: " . $to . "\n");
	$smtp->datasend("Subject: " . $oggetto . "\n");
	$smtp->datasend("Date: " . date_r() . "\n");
	$smtp->datasend("\n");
	$smtp->datasend($testo . "\n");
	$smtp->dataend();
	$smtp->quit;

}

sub date_r {
	my ($day, $mon, $str);
	my (@lt) = ();

	@lt     = localtime();
	$day    = $lt[6];
	$mon    = $lt[4];
	
	my @DAYS = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
	my @MON  = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Lug', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

	$str = 	$DAYS[$day] . ", " . 
		sprintf ("%2d", $lt[3]) . " " . 
		$MON[$mon] . " " . 
		($lt[5]+1900)
		. " " . sprintf("%02d:%02d:%02d", $lt[2], $lt[1], $lt[0] )
		. " " . sprintf("%03d%02d", (tz_offset() / 3600), 0);

	return $str;
}

return 1
