#!/usr/bin/perl

### patchdiag.xref location:
## https://getupdates.oracle.com/reports/patchdiag.xref


use strict;
use warnings;

### one arg -> path to patchdiag.xref
my $patchdiag_file = shift(@ARGV);

sub preparse_patchdiag {
	my @content;
	open(my $fh, $patchdiag_file) or die "bad file: $patchdiag_file, can't open\n";
	push(@content, $_) while(<$fh>);
	close($fh);
	return(grep(!/^#/, @content))
};

### legacy translation to numerical sortable date format. strptime is nice
### but our default perl 5.8.4 in solaris is stupid
sub date_converter {
        my %months = (
                jan => "01",
                feb => "02",
                mar => "03",
                apr => "04",
                may => "05",
                jun => "06",
                jul => "07",
                aug => "08",
                sep => "09",
                oct => "10",
                nov => "11",
                dec => "12",
        );
        my @bad_date = split(/\//, shift(@_)) or return("19700101");

        $bad_date[0] =~ tr/[A-Z]/[a-z]/;
        $bad_date[0] = $months{$bad_date[0]};
        if($bad_date[2] =~ /(0\d|1\d)/) {
                $bad_date[2] = "20$bad_date[2]";
        } else {
                $bad_date[2] = "19$bad_date[2]";
        };

        return(join("", @bad_date[2,0,1]));
};


### here we build hash with $patchid-$version as keys. See below
sub build_xref_hash {
	## local %xref_hash
	my %xref_hash;
	foreach(preparse_patchdiag()) {
		chomp(my @line = split(/\|/, $_));
		$xref_hash{"$line[0]-$line[1]"} = {};
		$xref_hash{"$line[0]-$line[1]"}{'date'} = $line[2];
		$xref_hash{"$line[0]-$line[1]"}{'flags'} = "@line[3..6]";
		$xref_hash{"$line[0]-$line[1]"}{'version'} = $line[7];
		$xref_hash{"$line[0]-$line[1]"}{'arch'} = $line[8];
		$xref_hash{"$line[0]-$line[1]"}{'pkgs'} = $line[9];
		$xref_hash{"$line[0]-$line[1]"}{'descr'} = $line[10];
		$xref_hash{"$line[0]-$line[1]"}{'xdate'} = date_converter($xref_hash{"$line[0]-$line[1]"}{'date'});
	};
	return(%xref_hash);
};

my %xref_hash = build_xref_hash();

### here we build helper hash of arrays having keys as xdates (above) to be able to list patches by days
sub build_xref_hash_xdate_ref {
	## local %xref_hash_xdate_ref
	my %xref_hash_xdate_ref;
	foreach(keys %xref_hash) {
		push(@{ $xref_hash_xdate_ref{$xref_hash{$_}{xdate}} }, $_);
	};
	return(%xref_hash_xdate_ref);

};

my %xref_hash_xdate_ref = build_xref_hash_xdate_ref();

#
#### debug and outputs ::
#

#foreach(keys(%xref_hash)) {
#	print "$xref_hash{$_}{'xdate'}; $_ $xref_hash{$_}{'descr'}\n"
#	print "$_; $xref_hash{$_}{'date'}; $xref_hash{$_}{'flags'}; $xref_hash{$_}{'descr'}\n"
#	print "$xref_hash{$_}{'date'}; $_\n";

#};


foreach(sort {$a <=> $b} grep(/^201005/, keys(%xref_hash_xdate_ref))) {
	my @tmp_list = @{ $xref_hash_xdate_ref{$_} };
	foreach(@tmp_list) {
		print "$xref_hash{$_}, $xref_hash{$_}{'date'}, $xref_hash{$_}{'flags'}, $xref_hash{$_}{'descr'}\n"
	};
};

