#! perl -wl
#$f1="/scratch/kenta/ghc/afs/sipb.mit.edu/project/ghc/arch/amd64_ubuntu1404/install/8.0.1-lts-7.7";
#$target="/hdd-scratch/kenta/ghc/713new/8.0.1-lts-7.13";
#$target="/scratch/kenta/ghc/afs/sipb.mit.edu/project/ghc/arch/amd64_ubuntu1404/install/8.0.1-lts-7.7";
#$target='/var/tmp/kenta/hdd/ghc/afs/sipb.mit.edu/project/ghc/arch/amd64_ubuntu1404/install/8.0.1-lts-7.16-a';
die unless defined $ARGV[0];
$target=shift @ARGV;

$cabalhome="$target/workarea/home";
#$cabalhome=$target;
open FI,"$cabalhome/.cabal/packages/hackage.haskell.org/00-index.cache" or die;
while(<FI>){
    next if /^pref-ver:/;
    die unless /^pkg: (\S+) ([0-9.]+) b# \d+$/;
    $p=$1;
    $v=$2;
    if($p eq 'find-conduit' or $p eq 'lambdabot-haskell-plugins' or $p eq 'lambdabot'){
        #lambdabot-haskell-plugins 5.1 infinite memory for prof build, 8.0.1
        #lambdabot depends on it

        #find-conduit 0.4.4 also infinite memory 8.0.1 (looks like GHC
        #Trac ticket 12425), bug may be fixed for 8.0.3 or 8.2

        print STDERR "blacklist $p-$v in $0";
        next;
    }
    $latest{$p}=$v;
}
$cconfig="$cabalhome/.cabal/config";
close FI;
open FI,$cconfig or die;
while(<FI>){
    if(/^constraint:/){
        die unless /^constraint: (\S+) == ([0-9.]+)$/;
        $already{$1}=$2;
    }
}
close FI;
open FI,"$target/bin/ghc-pkg list|" or die;
while(<FI>){
    next if /package\.conf\.d$/;
    next if /^\s*$/;
    die unless /^\s+(.+)/;
    $_=$1;
    if (s/^\((.*)\)/$1/){
        print STDERR "hidden $1";
    }
    die unless /^[a-zA-Z0-9]/;
    die unless /^(\S+)-([0-9.]+)$/;
    if(defined($already{$1})){
        print STDERR "diff $1 $already{$1} $2" if $already{$1} ne $2;
        next;
    }
    $already{$1}=$2;
    print STDERR "system $1";
}
# we end up not needing the version numbers in %latest

#additional packages not to consider
for$fn(@ARGV){
    print STDERR "excluding $fn";
    open FI,$fn or die;
    while(<FI>){
        chomp;
        die unless /(.*)-[0-9.]+$/;
        $already{$1}=1;
    }
    close FI;
}

for$p(sort keys%latest){
    next if defined$already{$p};
    $cmd="HOME=$cabalhome PATH=$target/bin:\$PATH $target/bin/cabal --config-file=$cconfig install -p --global --prefix=$target --dry-run --allow-newer --verbose=1 $p > dry-$p.out 2>&1";
    print$cmd;
}

# feed to deal-lines.hs
