#!/usr/bin/perl -w

use strict;
use DBI;
use Cache::FileCache;

my $debug = 0;

my $dbh = DBI->connect("DBI:Pg:dbname=gantt","","") || die $DBI::errstr;
my $cache = new Cache::FileCache();

my %omni;

sub db {
	return if (scalar keys %omni != 6);

	my $sql = "update gantt
		set finish=now() where
		sessionid='$omni{SessionID}' and
		type='$omni{Session_type}' and
		status='$omni{Session_status}' and
		user_group_host='".$omni{'User.Group@Host'}."' and
		specification='$omni{Backup_Specification}'";

	my $rv = $dbh->do($sql);

	print "sql:\n$sql\nrv: $rv\n" if ($debug);

	my ($device,$host);

	if ($rv eq "0E0" || !$rv) {
		my $c = $cache->get( $omni{SessionID} );

		if (defined $c) {
			($device,$host) = split(/\t/,$c,2);
			print STDERR "cache hit for $omni{SessionID} - $host:$device\n" if ($debug);
		} else {
			print STDERR "cache miss for $omni{SessionID}" if ($debug);
			open(O, "/usr/omni/bin/omnistat -session $omni{SessionID} |") || die "omnistat: $!";
			while(<O>) {
				chomp;
				next if (/^$/ || /^Device/ || /^=+$/);
				($device,$host,undef) = split(/\s+/,$_,3);
				$cache->set( $omni{SessionID}, "$device\t$host", "24 hours" );
				print STDERR " = $host:$device\n" if ($debug);
				last;
			}
			close(O);
		}
		
		$sql = "insert into gantt (sessionid,type,status,
			user_group_host,specification,device,host) values
			('$omni{SessionID}','$omni{Session_type}',
			'$omni{Session_status}',
			'".$omni{'User.Group@Host'}."',
			'$omni{Backup_Specification}',
			'$device','$host')";

		$dbh->do($sql) || warn "$sql : ".$dbh->errstr();

	}
}

open(O, "/usr/omni/bin/omnistat -detail |") || die "omnistat: $!";
while(<O>) {
	chomp;
	if (/^$/) {
		db();
		%omni = ();
		print "------------\n" if ($debug);
		next;
	}
	s/^[\t\s]+//;
	my ($l,$r) = split (/\s*:\s*/,$_,2);
	if ($r) {
		$l =~ s/\s+/_/g;
		$r =~ s/\s+$//g;
		print "$l -> $r\n" if ($debug);
		$omni{$l} = $r;
	}
}
db();
close(O);
