#!/bin/sh
# a script to update repository hashes and relink __softinka__.rpm
# to the lastest package; the latter part is based on 
# "sisyphus_cleanup_dups" from http://sisyphus.ru/srpm/sisyphus

# (c) 2006 by Michael Shigorin <mike@osdn.org.ua>
# for $CUSTOMER, covered by GPL

# Requires: apt-utils, rpm-utils
# Requires: rpm-build (due to /usr/bin/relative)

LC_COLLATE=C 

FTPDIR="/var/ftp/pub/Linux/Favorit/updates"
VERSION="1.0"
ARCH="i586"
COMPONENT="hasher"	# I've decided to leave it alone for easier rsync

__SOFTINKA__="__softinka__"	# dir/prefix for the special package
ARCHIVE="archive"	# pruned old versions recycle bin
DUPLIST=`mktemp`

fatal()
{
	echo $0: $* >&2
	exit 1
}

pushd "$FTPDIR/$VERSION" >/dev/null || fatal "Toplevel directory missing"
	# just in case
	mkdir -p "$ARCHIVE" "$__SOFTINKA__"
	# process dups
	pushd "$ARCH/RPMS.$COMPONENT" >/dev/null || fatal "RPMS directory missing"
		RPMDIR="`pwd`"
		for i in `ls -1 | grep ".$ARCH.rpm\$" | cut -c1 | sort -u`; do
			rpmrdups "$i"*.$ARCH.rpm >> "$DUPLIST" \
			|| fatal "rpmrdups failed (install rpm-utils?)"
		done
	popd >/dev/null
	[ -s "$DUPLIST" ] && {
		echo '*** dups found, moving to '$ARCHIVE:
		cut -d' ' -f2- -- "$DUPLIST" \
		| tr ' ' '\n' \
		| sort -u \
		| while read i; do
			mv -v "$ARCH/RPMS.$COMPONENT/$i" "$ARCHIVE"
		done
	}
	# now symlink current __softinka__ rpm to fixed location
	# NB: should be relative due to ftpd/rsyncd chrooting
	pushd "$__SOFTINKA__" >/dev/null
		__SOFTINKA___ABS="`ls "$RPMDIR/$__SOFTINKA__"-*.rpm 2>/dev/null`"
		[ -s "$__SOFTINKA___ABS" ] || fatal "missing or ambiguous $__SOFTINKA__ package"
		__SOFTINKA___FIXED="`pwd`/$__SOFTINKA__.rpm"
		( rpm --checksig "$__SOFTINKA___ABS" || fatal "rpm --checksig failed" ) \
		| fgrep -q ' NOT ' \
		&& fatal "ALERT: $__SOFTINKA___ABS IS CORRUPT, CHECKSUM MISMATCH!" \
		|| ln -sf "`relative "$__SOFTINKA___ABS" "$__SOFTINKA___FIXED"`" "$__SOFTINKA___FIXED"
	popd >/dev/null
	# finish with the rest
	echo
	echo '*** generating repository hashes:'
	genbasedir --topdir=. "$ARCH" "$COMPONENT" \
	|| fatal "genbasedir failed (install apt-utils?)"
popd >/dev/null

rm "$DUPLIST"
echo '*** done.'
