#!/usr/bin/perl
# fix multiple versions of same rpm (keep only the most recent version)

# for finding the common module
use lib qw(/usr/lib/libDrakX);

#i18n: IMPORTANT: to get correct namespace (dupeclean instead of libDrakX)
BEGIN { unshift @::textdomains, 'dupeclean' }

use strict;
#use warnings;

# for translating the script in other languages
use common;

# check if we are root
unless ($> == 0 || $< == 0) 
{
    die( N("You must be root to run this script.\n"));
}

# declare stuff
my ($rpm,$name);
my %seen = ();
my (@rpmlist,@dupelist) = ();
my $file = "/tmp/dupecleanresult";

# list all packages by install time in reversed order
@rpmlist = qx(rpm -qa --last);
chomp(@rpmlist);

# grab only rpm name to see if there's any duplicate in the list
# then format $rpm string so we can pass that to "rpm -e" command
foreach $rpm (@rpmlist) 
{
    if ( $rpm =~ /^(\S+)(-\S+-)(\S+pclos\d+)/ ) 
    {
      $name = $1;
      $rpm = $&;
      push(@dupelist, $rpm) if $seen{$name}++;
    }
}

# output result to terminal and file for reading into zenity dialog
if (@dupelist) 
{
  system("rpm -e @dupelist");
  print N"The following packages were removed: @dupelist\n";
  open FILE, ">$file";print FILE N("The following packages were removed: @dupelist\n");
} 
else 
{
  print N"No duplicate/multiple versions of rpms found.\n";
  open FILE, ">$file";print FILE N("No duplicate/multiple versions of rpms found.\n");
}

#unlink($file);

exit 0;
