#!/usr/bin/perl

my ($infile) = @ARGV;
my %idmap;
my %idRmap;
my %acctUsage;
my %shrUsage;
my %shrGrp;

#
# Need to get the association ID info so we get the proper
#   account with the proper name
#
open(ID,"sacctmgr -p -n show assoc format=id,user,account,grpcpumin|");
foreach my $line (<ID>){
	my ($id,$user,$acct,$grplim) = split(/\|/, $line);
	my $tag = "$acct|$user";
	#
	#  We seem to need a map both directions...
	#
	$idmap{$id} = "$tag";
	$idRmap{"$tag"} = $id;
}
close ID;

#
#  Read in job info 
#    Should look like Account|User|rawcputime
#
open(ACCT,"$infile");
my @act = <ACCT>;
close ACCT;
foreach my $line (@act){
        my ($acct, $user, $rawtime) = split (/\|/,$line);
        next unless ($rawtime > 0);
	my $tag = "$acct|$user";
	my $id = $idRmap{$tag};
        $acctUsage{$tag} += $rawtime;
}

#
# Read in the assoc_usage info
#   I saved the order of stuff to make sure I
#   wrote things in the same way they came in.
#     Not sure if it matters...
my @order;	
open(IN,"<assoc_usage");
# 
# binary mode input...
#
binmode(IN);
my $buff;
read(IN,$buff,2);
my ($vers) = unpack("n",$buff);
read(IN,$buff,8);
my ($time) = unpack("Q>",$buff);

unless($vers == 1){
	print "I'm not sure how to deal with version $vers...\n";
	exit(1);
}
print "$vers - $time\n";
print scalar localtime($time);
print "\n";
while (read(IN,$buff,16)){
	my ($id,$usage,$grp) = unpack("(IQI)>",$buff);
	$shrUsage{$idmap{$id}} = $usage;
	$shrGrp{$idmap{$id}} = $grp;
	push(@order,$id);
}
#
# Write out the same info, but use the account usage we got from sacct.
#
close(IN);
open(OUT,">newUsage");
binmode(OUT);
print OUT pack("n",1);
print OUT pack("Q>", time());
foreach my $id (@order){
	print OUT pack("(IQI)>",$id,$acctUsage{$idmap{$id}},$shrGrp{$idmap{$id}});
}
close OUT;
#
# Just for my info, how far were we between the two versions?
#
foreach my $tag (sort keys %shrUsage){
	my $diff = $acctUsage{$tag} - $shrUsage{$tag};
	print "$tag - $shrGrp{$tag} | $acctUsage{$tag} - $shrUsage{$tag} = $diff\n";
}
