#!/usr/bin/perl -w
use DB_File;
use RPM::Header;
use Fcntl;

die "Use: h-cleanup-pocket <pocket dir>" unless defined $ARGV[0];
die "Pocket not found: $ARGV[0]" unless -d $ARGV[0];
my $pocket = $ARGV[0];
chdir $pocket;

my %hash;
my $filename = "cache.db";

my $db = tie(%hash, 'DB_File', $filename, O_RDWR|O_CREAT, 0666, $DB_HASH)
	or die "Cannot open $filename: $!\n";

my @srpms = glob("SRPMS.*/*.src.rpm");
my %srpms;

foreach( @srpms )
{
	my $f = $_;
	$f =~ s/^.*\///;
	$srpms{$f}++;
}

my @rpms = glob("{i?86,x86_64}/RPMS.*/*.rpm");

# load RPMs to cache
foreach( @rpms )
{
	next if defined($hash{$_});
	my $srcrpm;
	{
		open( IN, "< $_" );
		my $hdr = new RPM::Header(\*IN) or die "$RPM::err";
		$srcrpm = $hdr->{SOURCERPM};
		close( IN );
	}
	$hash{$_} = $srcrpm;
}

foreach( @rpms )
{
	unlink $_ unless defined $srpms{$hash{$_}};
}

$db->sync();
undef $db;
untie %hash;


__END__

DISTRIBUTION=`dirname $(realpath $0)`

ls -1 $DISTRIBUTION/SRPMS.*/*.src.rpm  \
	| sed 's/^.*\///' \
	| sort -u > list.srpms
ls -1 $DISTRIBUTION/{i?86,x86_64}/RPMS.*/*.rpm | while read f; do
	SOURCERPM=`rpm -qp --qf '%{SOURCERPM}' "$f"`
	echo $SOURCERPM
done
exit

reps="$DISTRIBUTION/i?86/RPMS.*"
echo  $DISTRIBUTION/x86_64/RPMS.hasher
if [ -d $DISTRIBUTION/x86_64/RPMS.hasher ]; then
	reps="$reps $DISTRIBUTION/x86_64/RPMS.*"
else
	echo "x86 only"
fi
reps="$reps $DISTRIBUTION/SRPMS.*"
for rep in $reps; do
	mkdir -p -m700 -- "$WORKDIR/$rep"
	pushd "$PREFIX/$rep" >/dev/null
	(
		echo "entering $rep."
		>"$WORKDIR/$rep/dups" || { echo "failed $rep."; exit 1; }
		for n in `ls -1 |grep '.rpm$' |cut -c1 |LC_COLLATE=C sort -u`; do
			rpmrdups "$n"*.rpm >>"$WORKDIR/$rep/dups" &&
			echo "done $rep/$n." ||
			{ echo "failed $rep/$n."; exit 1; }
		done
		echo "leaving $rep."
	) &
	popd >/dev/null
done
echo "Waiting for rpmrdups..."
wait

echo "Done."

for rep in $reps; do
	if [ -s "$WORKDIR/$rep/dups" ]; then
		echo "Duplicated files found in \"$rep\" repository:"
		cat -- "$WORKDIR/$rep/dups"
		echo

		pushd "$PREFIX/$rep" >/dev/null
			cut -d\  -f2- -- "$WORKDIR/$rep/dups" |xargs -r ls -Llt --
			while :; do
				echo "Really purge files listed above? (yes/no)"
				read
				if [ "$REPLY" = no ]; then
					echo Cancelled!
					continue 2;
				fi
				if [ "$REPLY" = yes ]; then
					break;
				fi
			done

			cut -d\  -f2- -- "$WORKDIR/$rep/dups" |xargs -r realpath |xargs -r rm -v --
		popd >/dev/null
	fi
done

./gen
