#!/bin/ash -eu
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*- 
# $Id: gaffer,v 0.0.1 2006/03/13 17:43:03 legion Exp $ 

. "${0%/*}/../config"
. "$dist/incominger/functions"

src="$incdir/check"

TEST=
NOMAILS=

writelog() {
	hsh-run "$workdir" -- "/.host/prog.ash" "/.in/$1" > "$logdir/$1.info" ||
	    { logit "FATAL	Unable get rpm owner: $1"; return 0; }

	cat >"$logdir/$1.log"<<EOF
This package is either the same or older than already existing package.
EOF
	logit "reject	$1"    
}

[ -d "${logfile%/*}" ] || mkdir -p "${logfile%/*}"
cd "$repo/files/SRPMS"

# Build chroot
"$helpers/initchroot" -c -a "$apt_dir/apt.conf" -- "$workdir" ash

# Install helper programs
install -m 755 -- "$helpers/getowner" "$workdir/chroot/.host/prog.ash"

logdir="$logsdir/$PROG/$stamp"
mkdir -p "$logdir" || fatal "cannot create directory \`$logdir': File exists"

find "$src/" -name '*.src.rpm' |
while read p; do
    f="$(readlink -ve "$p")" || continue
    fn="${f##*/}"

    rm -rf -- "$workdir/chroot/.in/"*

    [ -f "./$fn" ] &&
	rsync -a -- "$f" "$workdir/chroot/.in/" &&
	$TEST rm -f -- "$f" && 
	writelog "$fn" ||:

    [ -f "$f" ] || continue

    rsync -a -- "$f" "$workdir/chroot/.in/" || continue
    
    rpm_name="$(hsh-run "$workdir" -- rpmquery -p --qf='%{name}' "/.in/$fn")" ||
        { logit "FATAL	Unable get rpm name: $fn"; continue; }

    list="$(find "./" -name "$rpm_name*.src.rpm" -printf %f\\n)" ||
	{ logit "FATAL	Unable get rpm list: $fn"; continue; }

    [ -n "$list" ] && 
	rpmrdups "$f" $list | cut -d\  -f2- | fgrep -qs "$fn" &&
	$TEST rm -f -- "$f" &&
	writelog "$fn" ||:
done
hsh_cleanup

[ -n "$NOMAILS" ] || 
    "$helpers/sendmails" ${TEST:+-T} -- "$logdir"

remove_if_empty "$logdir"
