#!/usr/bin/perl
# cpanel10 - yumduprpmfix                         Copyright(c) 2005 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cpanel license. Unauthorized copying is prohibited

exit() if ( !-e '/var/cpanel/useyum' );

print "This script will attempt to locate and resolve any\n";
print "duplicate rpms on the system. Any files removed\n";
print "will be archived in /root/rpm_dups.tar\n";
print "The tar ball may be removed at your discretion.\n";

open( YUM, '/etc/yum.conf' ) || die "Unable to open yum.conf: $!";
my @yum = <YUM>;
close(YUM);
my @newyum = grep( !/^exclude=/, @yum );
open( YUM, '>', '/etc/yum.conf' );
print YUM join( '', @newyum );
close(YUM);

my @dups;
my %RPMS;

open( RPMQA, '-|' ) || exec( 'rpm', '-qa' );
while (<RPMQA>) {
    chomp();
    my $rpm = $_;
    next if ( $rpm =~ /pubkey/ );
    if ( exists( $RPMS{$rpm} ) ) {
        push( @dups, $rpm );
    }
    else {
        $RPMS{$rpm} = 1;
    }
}
close(RPMQA);

my @remove;

foreach my $rpm (@dups) {
    print "[[ Fixing $rpm ... \n";
    my @rpmlist;
    open( RPMQL, '-|' ) || exec( 'rpm', '-ql', $rpm );
    while (<RPMQL>) {
        chomp();
        push( @rpmlist, $_ );
    }
    close(RPMQL);
    my @rpmparts = split( /\-/, $rpm );
    my @rpmname;
    foreach (@rpmparts) {
        if (/^[a-z]/i) {
            push( @rpmname, $_ );
        }
    }
    my $rpmnew = join( '-', @rpmname );
    print "system('rpm','-e','--allmatches','--justdb','--nodeps',$rpmnew)\n";
    system( 'rpm', '-e', '--allmatches', '--justdb', '--nodeps', $rpmnew );
    print "system('yum','-y','install',$rpmnew)\n";
    system( 'yum', '-y', 'install', $rpmnew );
    foreach my $file (@rpmlist) {
        next if ( !-e $file );
        print "Checking file $file\n";
        my $rpmquery = `rpm -qf $file`;
        if ( $rpmquery =~ /not owned/ ) {
            if ( !-d $file ) {
                push( @remove, $file );
            }
        }
    }
    print " ... Done ]]\n";
}

foreach (@remove) {
    system( 'tar', '-rpf', '/root/rpm_dups.tar', $_ );
    system( 'rm', '-fv', $_ );
}

open( YUM, '>', '/etc/yum.conf' );
print YUM join( '', @yum );
close(YUM);
