#!/bin/bash -e
IS_FORCE=0

if [ "$1" = "-f" ]; then
	shift;
	IS_FORCE=1
fi

if [ "$1" = "" ]; then
	echo "Use: $0 <dirname>" > /dev/stderr
	exit -1
fi

WORKDIR="`mktemp -dt dups.XXXXXXXXXX`"

exit_handler()
{
        local rc=$?
        trap - EXIT
        rm -rf -- "$WORKDIR"
        exit $rc
}
trap exit_handler EXIT HUP INT PIPE TERM QUIT

echo "Making dups in repositories..."

DISTRIBUTION="$1"

if [ -z "$DISTRIBUTION" ]; then
	DISTRIBUTION=`dirname $(realpath $0)`
fi

DISTRIBUTION=`realpath "$DISTRIBUTION"`
cd "$DISTRIBUTION"

#ls -1 $DISTRIBUTION/{i?86,x86_64}/RPMS.*/*.noarch.rpm 2> /dev/null | while read f; do
#	T=`echo "$f" \
#		| sed 's/\/[^\/]*$//' \
#		| sed 's/^.*\/RPMS\.//'`
#	mv -f $f $DISTRIBUTION/noarch/RPMS.$T/
#done

reps="$DISTRIBUTION/i?86/RPMS.*"
reps="$reps $DISTRIBUTION/noarch/RPMS.*"
reps="$reps $DISTRIBUTION/x86_64/RPMS.*"
reps="$reps $DISTRIBUTION/SRPMS.*"
for rep in $reps; do
	[ -d "$rep" ] || continue
	echo "rep: $rep"
	mkdir -p -m700 -- "$WORKDIR/$rep"
	pushd "$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 "$rep" >/dev/null
			cut -d\  -f2- -- "$WORKDIR/$rep/dups" |xargs -r ls -Llt --
			while :; do
				[ "$IS_FORCE" = "1" ] && break
				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

h-gen "$DISTRIBUTION"
