#!/bin/sh -e
#
# Copyright (C) 2005  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2008  Alexey Tourbin <at@altlinux.org>
# 
# sisyphus_gen_contents script.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#

export LANG=C LANGUAGE=C LC_ALL=C

PROG="${0##*/}"

[ $# -eq 1 ] || { echo "Usage: $PROG <directory>" >&2; exit 1; }

cd "$1"
shift

WORKDIR=
exit_handler()
{
	local rc=$?
	trap - EXIT
	[ -z "$WORKDIR" ] || rm -rf -- "$WORKDIR"
	exit $rc
}

trap exit_handler HUP INT QUIT TERM EXIT

WORKDIR="$(mktemp -d -t "$PROG.XXXXXXXXXX")"

# generate filelist.
find -mindepth 1 -maxdepth 1 -name \*.rpm -print0 |
	xargs -r0 rpmquery -p --qf '[%{FILENAMES}\t%{NAME}\n]' -- |
	fgrep -v ' ' |
	sort -u >"$WORKDIR"/f-list

# generate path-like provides list.
find -mindepth 1 -maxdepth 1 -name \*.rpm -print0 |
	xargs -r0 rpmquery -p --qf '[%{PROVIDENAME}\t%{NAME}\n]' -- |
	grep '^/' |
	fgrep -v ')' |
	fgrep -v ' ' |
	sort -u >"$WORKDIR"/p-list

cd "$WORKDIR"

# find file dups.
cut -f1 <f-list |
	uniq -c |
	awk '{if ($1 != "1") printf("%s\t%s\n",$2,$2)}' >f-dups

# generate alternatives-like virtual path list.
comm -13 f-list p-list >vp-list

# virtual paths should always map to themselves.
cut -f1 <vp-list |
	awk '{printf("%s\t%s\n",$1,$1)}' >vp-force-dups

sort -u -k1,1 vp-force-dups f-dups f-list
