#!/usr/bin/env perl

use strict;
use warnings;

$0=~m#(.*)/# or die "Bad call path!";
my $ddir = "$1/../docker";
chdir($ddir);

my $dh = undef;
opendir($dh, '.') or die "Could not read dir '.', because: $!";

my %where = ();

while(my $fn = readdir($dh)) {
  next if $fn=~m#^\.#;
  next unless -d $fn;
  print "=== $fn ===\n";
  my $df = "$fn/Dockerfile";
  if(!-e $df) {
    print "No Dockerfile here.\n\n";
    next
  }
  my $fh = undef;
  my @dep = ();
  open($fh, '<', $df) or die "Could not read '$df', because: $!";
  while(my $line = <$fh>) {
    if($line=~m#^\s*RUN\s+apt(?:-get|itude|)\s+(.*)#i) {
      my $what = $1;
      my @what = grep {!m#^-#} grep {length} split /\s+/, $what;
      if(@what) {
        my $inst = shift @what;
        if('install' eq $inst) {
          push @dep, @what
        }
      }
    }
  }
  print "Packages found: @dep\n\n";
  for(@dep) {
    push @{$where{$_}}, $fn
  }
}

print "\n\n\n";

my %byDocker = ();

for my $pa(sort keys %where) {
  my $l = $where{$pa};
  print ":: $pa: @$l\n";
  my @l = sort @$l;
  my $nk = "@l";
  push @{$byDocker{$nk}}, $pa;
}

print "\n\n\n";

for my $do(sort {length $a <=> length $b || $a cmp $b} keys %byDocker) {
  my @sp = sort @{$byDocker{$do}};
  print "!! $do\n@sp\n\n";
}



