#!/usr/bin/perl -w
use strict;

my $lastname = 0;
my $lastversion;
my $lastext;
my @stalefiles;
my @files;

# Insert your exclusions here with trailing '-'
my %maskedfiles = (
   'X420src-' => 1,
   'gcc-' => 1,
   'freetype-' => 1
);

# Root check
#if ($< != 0) {
#   print "You must be root to run this script.\n";
#   exit 0;
#}

# Determine sources present on the system
print "Determining available tarballs in /usr/portage/distfiles ...\n";
opendir(DIR, "/usr/portage/distfiles");
@files = sort(readdir(DIR));
closedir(DIR);

# Grab names/versions, checking each time whether current distfile
# has been superceded. Push anonymous array ref containing required
# info into @stalefiles array.
print "Determining stale versions ...\n";
foreach (@files) {
   my $name;
   my $version;
   # Only operate on tarballs   
   if (/(.+?\-)([0-9r\.\-]+)(\.tar\.gz|\.tgz|\.tar.bz2)/s) {
      $name = $1;
      $version = $2;
      next if ($maskedfiles{$name}); # Ignore "masked" files
      if ($lastname && $name eq $lastname) {
         if ($version gt $lastversion) {
            push (@stalefiles, [$name, $version, $lastversion, $lastext]);
         }
      }
      $lastname = $name;
      $lastversion = $version;
      $lastext = $3;
   }
}

if (@stalefiles == 0) {
   print "\nNo stale distfiles have been detected on your system!\n";
   exit 0;
}

if ($ARGV[0] && $ARGV[0] eq '--nopretend') {
   # User requested deletion so here goes ...
   print "*Nopretend* mode, deleting stale files:\n\n";
   foreach (@stalefiles) {
      my ($name, $version, $lastversion, $ext) = @{$_};
      unlink('/usr/portage/distfiles/' . $name . $lastversion . $ext);
      print "Deleted: $name$lastversion in favour of $name$version\n";
   }
}
else
{
   # Safe mode (default)!
   print "\7*Pretend* mode, will only pretend to delete files.\nTo actually delete the files, reinvoke with the --nopretend parameter.\n\n";
   foreach (@stalefiles) {
      my ($name, $version, $lastversion, $ext) = @{$_};
      print "Would delete: $name$lastversion in favour of $name$version\n";
   }
}
1;
