#!/usr/bin/perl -w
use common::sense;

use DateTime;
use File::Basename qw( fileparse );
use File::Find qw( find );
use File::Spec::Functions qw( catfile catdir splitdir );
use File::Path qw(make_path);

my ( $dirs, $files, $rmdirs, $rmfiles, $zstdfiles ) = ( {}, {}, {}, {}, {} );

find(
    sub {
	if (m/\Asetup_current\Z/) {
	    $File::Find::prune = 1;
	    return;
	}
	my ( $fd, $fdn, $fn ) = ( $File::Find::dir, $File::Find::name, $_ );
	my @fs = lstat $_;
	if (-f _) {
	    my ( $bn, undef, $bs  ) = fileparse( $fn, qw( .bz2 .xz .zst ) );
	    return unless $bs;
	    my @pd = splitdir $fd;
	    my $pdn = catfile @pd[1..$#pd], $bn;
#	    say "$fd => $pd[0] ($bs): $pdn = $fs[7]" if (/guile/);
	    $files->{$pdn}{$pd[0]} = [ $bs, @fs[7,9] ];
	} elsif (-d _) {
	    my @pd = splitdir $fdn;
	    my $pdn = catdir @pd[1..$#pd];
#	    say "$fdn => $pd[0]: $pdn" if (/guile/);
	    $dirs->{$pdn}{$pd[0]}++;
	}
    }, qw( install install-zstd ));
foreach my $fn ( reverse sort keys %$files ) {
    my %f = %{$files->{$fn}};
    my ( $i, $z ) = @f{qw( install install-zstd )};
    if (defined $i and not defined $z) {
#	say "Only in install:      $fn";
	# make path & recompress file
	$zstdfiles->{$fn} = $i;
    } elsif (defined $z and not defined $i) {
#	say "Only in install-zstd: $fn";
	# remove file
	$rmfiles->{$fn}++;
    } else {
	# make path & recompress if zstd file is older
	$zstdfiles->{$fn} = $i if ($i->[2] gt $z->[2]);
    }
}
foreach my $dn ( reverse sort keys %$dirs ) {
    my %d = %{$dirs->{$dn}};
    my ( $i, $z ) = @d{qw( install install-zstd )};
#    say "$dn" if ($dn =~ m/guile/);
    if (defined $i and not defined $z) {
#	say "Only in install:      $dn";
	# make path
	say STDERR "mkdir install-zstd/$dn.zst";
	make_path "install-zstd/" . $dn;
    } elsif (defined $z and not defined $i) {
#	say "Only in install-zstd: $dn" ;
	# remove directory
	$rmdirs->{$dn}++;	
    }
}
foreach my $fn ( reverse sort keys %$rmfiles ) {
    say STDERR "rm    install-zstd/$fn";
    unlink "install-zstd/" . $fn . ".zst";
}
foreach my $dn ( reverse sort keys %$rmdirs ) {
    say STDERR "rmdir install-zstd/$dn";
    rmdir "install-zstd/" . $dn;
}
foreach my $zn ( sort { $zstdfiles->{$b}[1] <=> $zstdfiles->{$a}[1] } keys %$zstdfiles ) {
    say STDERR sprintf( "%12i", $zstdfiles->{$zn}[1] ), " # ",
	DateTime->from_epoch(epoch=>$zstdfiles->{$zn}[2])->iso8601(), "\t",
	"$zn$zstdfiles->{$zn}[0]";
    say "$zn$zstdfiles->{$zn}[0]";
}
