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

TEST=
NOMAILS=

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

src="$incdir/check"
dst="$incdir/perms"

"$helpers/dups" "$src"

[ -d "${logfile%/*}" ] || mkdir -p "${logfile%/*}"

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

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

logdir="$logsdir/${src##*/}/$stamp"
mkdir -p "$logdir" || fatal "cannot create directory \`$logdir': File exists"

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

    rm -rf -- "$workdir/chroot/.in/"*
    rsync -a -- "$f" "$workdir/chroot/.in/" || continue

    if ! hsh-run "$workdir" -- sisyphus_check -v --files "/.in/$fn" >"$logdir/$fn.log" 2>&1; then
        hsh-run "$workdir" -- "/.host/prog.ash" "/.in/$fn" > "$logdir/$fn.info" ||
    	    { logit "FATAL	Unable get rpm owner: $fn"; continue; }
	logit "reject	$fn"
	$TEST rm -f -- "$f"
	continue
    fi

    $TEST rsync -a --remove-sent-files -- "$f" "$dst/"
    rm -f -- "$logdir/$fn.log"
    logit "accept	$fn"
done
rm -rf -- "$workdir/chroot/.in/"*

cd "$src"
for n in `ls -1 "$src/" |grep ".src.rpm\$" |cut -c1 |LC_COLLATE=C sort -u`; do
    rpmrdups "$n"*.src.rpm | cut -d\  -f2- | tr \  \\n | 
    while read p; do
	f="$(readlink -e "$p")" || continue
	fn="${f##*/}"

	if [ ! -f "$logdir/$fn.info" ]; then
	    rm -rf -- "$workdir/chroot/.in/"*
	    rsync -a -- "$f" "$workdir/chroot/.in/" || continue
	    hsh-run "$workdir" -- "/.host/prog.ash" "/.in/$fn" > "$logdir/$fn.info" ||
		{ logit "FATAL	Unable get rpm owner: $fn"; continue; }
	fi
	cat >>"$logdir/$fn.log"<<EOF
This package is either the same or older than already existing package.
EOF
	$TEST rm -f -- "$f"
    done
done

# Cleanup chroot
hsh_cleanup

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

remove_if_empty "$logdir"
