#!/bin/bash

# rpmdup_remover finds duplicate packages and deletes them all from the rpm 
# database, leaving the *oldest* version intact. After a successful run, the user
# should then issue a "yum update" command to install the latest package versions.

# Version 0.9.4   2008-12-04
# Written by Alan Bartlett <ajb@elrepo.org>
# Based on the original logic of Akemi Yagi <toracat@centos.org> and ably assisted
# in testing & debugging by Richard Chapman <rchapman@aardvark.com.au>

PROGNAME=`basename $0`
TMPFILE=/var/tmp/rpmdup_$$
RPMFLAGS='-e --nodeps --justdb --test'

trap 'echo -e "\n$PROGNAME: aborted."; rm -f $TMPFILE*; exit 1' 1 2 3 15

usage() {
	echo "usage: $PROGNAME [ --notest ]"
}

if [ $# -gt 1 ]; then
	usage
	exit 2
elif [ $# -eq 1 ]; then
	if [ "$1" == "--notest" ]; then
		RPMFLAGS='-e --nodeps --justdb'; else
		usage
		exit 3
	fi
fi

rpm -qa --qf "%{NAME} %{ARCH}\n" | grep -v ^gpg-pubkey | grep -v ^kernel | sort | uniq -c > $TMPFILE-1

awk '$1 != 1 && $3 ~ /noarch/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-noarch
	done

awk '$1 != 1 && $3 ~ /i386/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-i386
	done

awk '$1 != 1 && $3 ~ /i486/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-i486
	done

awk '$1 != 1 && $3 ~ /i586/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-i586
	done

awk '$1 != 1 && $3 ~ /i686/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-i686
	done

awk '$1 != 1 && $3 ~ /x86_64/ { print $2 }' $TMPFILE-1 | while read package
	do rpm -q --last $package | head -n -1 | cut -d" " -f1 >> $TMPFILE-2-x86_64
	done

for arch in noarch i386 i486 i586 i686 x86_64; do
	if [ -f $TMPFILE-2-$arch ]; then
		while read package; do
			rpm -q --qf "%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" $package.$arch >> $TMPFILE-3
		done < $TMPFILE-2-$arch
	fi
done

if [ -f $TMPFILE-3 ]; then
	uniq $TMPFILE-3 | while read package; do
		echo rpm $RPMFLAGS $package
		rpm $RPMFLAGS $package
	done
fi

rm -f $TMPFILE*

exit 0

