# perl
use warnings;
use 5.12.0;
use Data::Dumper;$Data::Dumper::Indent=1;
use Data::Dump qw( dd pp );
use Carp;
use Cwd;
use CPAN::DistnameInfo;

my $cwd = cwd();

croak "Must supply file in current directory as command-line argument"
    unless (@ARGV == 1 and -f $ARGV[0]);

my $fails_file = shift(@ARGV);
my %failures = ();
my $rank = 0;
open my $IN, '<', $fails_file or croak "Unable to open $fails_file for reading";
while (my $l = <$IN>) {
    chomp $l;
    my @these_fails = ();
    if (
        ((@these_fails) = $l =~ m/Module '([^']+?)' is not installed/g) or
        ((@these_fails) = $l =~ m/Installing\s(\S+?)\sfailed/g) or
        ((@these_fails) = $l =~ m/Already tried (\S+?)\.\s+Skipping\./)
    ) {
        # okay
    }
    elsif ($l =~ m/FAIL Bailing out the installation for (\S+)\.$/) {
        my $frag = $1;
        push @these_fails, fragment_matcher($frag);
    }
    else {
        next;
    }
    for my $mod (@these_fails) {
        next unless defined $mod;
        if (! exists $failures{$mod}) {
            $failures{$mod}{count} = 1;
            $failures{$mod}{rank}  = ++$rank;
        }
        else {
            $failures{$mod}{count}++;
        }
    }
}
close $IN or croak "Unable to close $fails_file after reading";
#dd(\%failures);

for my $mod ( sort { $failures{$a}{rank} <=> $failures{$b}{rank} } keys %failures) {
    printf "%3d  %-50s%6d\n" => ($failures{$mod}{rank}, $mod, $failures{$mod}{count});
}

say STDERR "Finished";


sub fragment_matcher {
    my $bail = shift;
    my $s = "${bail}*";
    my $id_dir = '/home/jkeenan/minicpan/authors/id';
    my $pathname = `find $id_dir -type f -name $s`;
    
    my $d = CPAN::DistnameInfo->new($pathname);
    croak "constructor did not return object"
        unless (defined $d and ref($d) eq 'CPAN::DistnameInfo');
    my ($dist, $mod);
    $dist = $d->dist;
    unless (defined $dist) {
        carp "Problem with '$bail'";
        return;
    }
    $mod = $dist =~ s/-/::/gr;
    return $mod;
}

