#! perl -lw
# parametrized version of process-dryrun2 for better use in scripts.
die unless defined($outdir=$ARGV[0]);
open S1,">$outdir/singles.list" or die;
open S2,">$outdir/multiples.list" or die;
open BAD,">$outdir/bad.list" or die;
while(defined($fn=<STDIN>)){
    chomp$fn;
    die unless $fn=~/\/DR-(.*?)\.out$/;
    $p=$1;
    open FI,$fn or die;
    while(<FI>){
        chomp;
        #Warning the package list is old.
        #Run 'cabal update' to get the latest list
        last if /Resolving dependencies\.\.\./;
    }
    unless(defined$_){
        print STDERR "ERROR failed to find Resolving dependencies $fn";
        close FI;
        next;
    }
    unless($_ eq "Resolving dependencies..."){
        print STDERR "ERROR weird 1st line $fn";
        close FI;
        next;
    }
    $good=1;
    $bad=0;
    $todo=0;
    undef$pversion;
    undef@deps;
    while(<FI>){
        chomp;
        #next if /user/ and /system/ and /elapsed/ and /avgtext/ and /avgdata/ and /maxresident/;
        #next if /inputs/ and /outputs/ and /major/ and /minor/ and /pagefaults/;
        if(/Could not resolve dependencies/){
            $good=0;
            $bad=1;
        }
        if (/\(latest: [0-9.]+\)$/){
            if (defined($ENV{lax_latest})){
                s/ \(latest: [0-9.]+\)//;
            } else {
                $good=0;
            }
        }
        if (/internal error: could not construct a valid install plan/){  # edentv-4.10.0, lts-7.18
            $good=0;
            print STDERR "ERROR $fn $_";
        }
        if(/^In order, the following would be installed/){
            $todo=1;
            next;
        } else {push@deps,$_}
        if(/All the requested packages are already installed/){
            print STDERR "ERROR duplicate $fn";
            $good=0;
        }
        $good=0 if /The following packages are likely to be broken by the reinstalls/;
        if($todo){
            $good=0 if /\(/;
            # the above gets things like (reinstall)
            $pversion=$_;
        }
    }
    close FI;
    if($bad){
        print BAD $p;
    }
    next unless$good;
    die "ERROR not todo $fn" unless $todo;
    if (@deps == 0){
        die "ERROR no lines $fn";
        next;
    } else {
        $a=pop@deps;
        die unless defined($pversion);
        die unless $a eq $pversion;
        $a =~ /(.+)-[0-9.]+$/;
        die "ERROR $1 and $p are different" unless ($1 eq $p) or ($a eq $p);
        if (@deps == 0){
            print S1 $pversion;
        } else{
            print S2 $pversion;
        }}
}
