#!/usr/bin/perl
#
use File::Path qw(make_path);

$file = "all";
$fsum  = "md5sums";
$smode = open( SFILE, "s_$fsum" );
if( defined $smode )
{
  $dmode = open( DFILE, "d_$fsum" );
  if( !defined $dmode )
  {
    close( SFILE );
    open( SFILE, "> d_$fsum" ) || die "create d_$fsum - $!\n";
  }
  else
  {
    %h = ();
    while( <DFILE> )
    {
      ($k, $v) = split;
      $h{$k} = $v;
    }
    close( DFILE );
    while( <SFILE> )
    {
      ($k, $v) = split;
      if( defined $h{$k} )
      { 
        @dirs = split( /\//, $v );
        pop @dirs;
        make_path( join( '/', @dirs ), { mode => 0755 });
        rename( "$h{$k}", "$v" );
        printf( "$h{$k} -> $v\n"); 
      } 
    }
    close( SFILE );
    exit;
  }
}
else
{
  open( SFILE, "> s_$fsum" ) || die "create s_$fsum - $!\n";
}

open( IFILE, "$file" ) || die "open $file - $!\n";
print( "Filtering file: $file\n" );
while( $ln = <IFILE> )
{
  $ln =~ s/[\r\n]*$//;
  next if( $ln =~ /^$/ );
  next if( $ln =~ /^(building|sent|Linux|total)\s/ );
  next if( $ln =~ /\/$/ );
  if( defined $smode ) { next if( $ln !~ /^deleting\s/ ); }
  else { next if( $ln =~ /^deleting\s/ ); }
  $ln =~ s/^deleting\s+//;
  $ln = `md5sum "$ln"`;
  print( SFILE "$ln" );
}
close( IFILE ) || die "close $file $!\n";
close( SFILE );
exit;
# end
