#!/bin/env perl -lw
#
# $Id: killdupes 2484 2008-12-09 10:20:31Z dmichelsen $
#
# Copyright 2006 Cory Omand <comand@blastwave.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This software is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# killdupes - Remove duplicate packages from a directory, with or
#             without user interaction.  Note that this only works
#             for packages named according to package standards.
#

use strict;
use File::Basename;
use Getopt::Std;
use Data::Dumper;
use vars qw/$opt_n/;

getopts ":n";

my %packages;
foreach my $file (@ARGV) {
    my $bn = basename $file;
    my ($pkg,$ver) = split /-/, $bn, 3;
    push @{$packages{$pkg}}, $file;
}

foreach my $pkg (sort keys %packages) {
    if (scalar @{$packages{$pkg}} > 1) {

        my @unlink;
        if ($opt_n) {
            # Non-interactive
            my %finfo;
            foreach my $file (@{$packages{$pkg}}) {
                $finfo{$file} = (stat($file))[9];
            }
            @unlink = sort {$finfo{$a} <=> $finfo{$b}} keys %finfo;
            pop @unlink;
        }
        else {
            # Write dupes out to a tempfile
            my $tfile = "/tmp/kd.$pkg.$$";
            open TFILE, ">>$tfile" or die "Cannot open file: $!";
            print TFILE foreach @{$packages{$pkg}};
            close TFILE;

            # Use ckitem for menu selection
            my ($rst) = `ckitem -p "Keep which file" -f $tfile`;
            unlink $tfile;

            chomp $rst; last if $rst eq 'q';
            @unlink = grep { !/$rst/ } @{$packages{$pkg}};
        }
        foreach (@unlink) { print "unlink: $_" ; unlink or die }

    }
}
