#!perl -nlw
#analyze singles-install log
print if /:  Died/;
print if /:  ERROR /;
if(/:  Completed\s+\S+-[0-9.]+$/){  #was "Installed" in an older version of cabal
    $explained=0;
    $do_message=0;
    # NOTE there are a few Permission denied but success items
}elsif(/Missing \(or bad\) C libr/  or /:\d+:\d+: fatal error:/ or /Missing \(or bad\) header/ or /Bad header file:/ or /an out-of-memory/ or /ghc: panic/ or /could not execute/ or /: The program .* is required but / or /exec: permission denied/ or /error: undefined reference to / or /runInteractiveProcess: exec: does not exist/ or /Simplifier ticks exhausted/ or /:  : copyFile: does not exist \(No such file or directory\)/){
    # these are fixable
    #The "Missing (or bad) header message is confusing, it usually
    #means "bad", even though the bad header is usually trying to
    #recursively include something missing.

    #from cabal/Cabal/Distribution/Simple/Configure.hs

    print "> $_";
    $do_message=1;
    if (/Missing \(or bad\) C library: (\S+)/) {
        &apt_file($1);
        #system('apt-file','search','-x',"/lib$1\\.so\$");
        # because we need to the search inside the container
    }elsif (/Missing \(or bad\) C libraries: (.+)/) {
        $r=$1;
        @F=split /,\s*/,$r;
        undef %h;
        for(@F){
            $h{$_}=1; #merge duplicates
        }
        for (sort keys %h){
            &apt_file($_);
        }
        if($r=~/,\s*$/){
            print "WARNING: next line not processed";
        }

    }
}elsif (/:\d+(-\d+)?:\d+(-\d+)?: error:$/ or /(hs|hsc):\d+(-\d+)?:\d+(-\d+)?: error: / or /<no location info>: error: / or /No libraries, executables, tests, or benchmarks are enabled for package/ or /Failing due to -Werror/ or /depends on.*which failed/ or /:  ghc: unrecognised flag/ or /No executables and no library found\. Nothing to do\./ or /The package has an impossible version range for a dependency/ or /File in tar archive is not in the expected directory/ or /ghc: on the commandline: malformed integer argument in -Odph/ or /installed package info from too old version of Cabal \(key field does not match id field\)/ or /on the commandline: error: \[-Werror\]/){
        $explained=1;
}elsif (/ROOT FAILURE/){
    if ($do_message or ! $explained){
        print "UNEXPLAINED " unless $do_message;
        print "$_\n";
    }
    $explained=0;
    $do_message=0;
}

sub apt_file {
    my$lib=shift;
    my$container='ghcbuild';
    $container = $ENV{container} if defined$ENV{container};
    $lib =~ s/(\+)/\\$1/g;  # c++
    print "SHELL lxc-attach -n $container -- env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin sudo -u iuser apt-file search -x '/lib$lib\\.so\$'";
}
