#!/bin/bash
set -e
failed=0
good=0
rm -rf output
mkdir -p rpms
cp -rl rpms output

if [ -z "$1" ]; then
	specs=(tests/*.spec)
else
	specs=("$@")
fi
rpmlint=/opt/testing/bin/rpmlint
if [ ! -x "$rpmlint" ]; then
	rpmlint="${rpmlint##*/}"
	if ! rpmlint --help >/dev/null 2>/dev/null; then
		echo "rpmlint not installed"
		exit 1
	fi
	echo "using system rpmlint"
fi
check()
{
	local name="$1"
	shift
	if [ -e tests/$name.ignore ]; then
		if [ "${rpmlint:0:1}" = r ]; then
			set -- -f "$PWD/tests/$name.ignore" "$@"
		else
			RPMLINT_MINI_CONFIG="$PWD/tests/$name.ignore"
			export RPMLINT_MINI_CONFIG
		fi
	else
		unset RPMLINT_MINI_CONFIG
	fi
	set -- $rpmlint "$@"
	if [ -e tests/$name.env ]; then
		local line
		local env=()
		while read line; do
			env+=("$line")
		done < tests/$name.env
		set -- env "${env[@]}" "$@"
	fi
	"$@"
}
for i in "${specs[@]}"; do
	echo "building $i ..."
	rpmbuild --quiet --define "_rpmdir $PWD/output/packages" -bb $i
done
find output/packages -name '*.rpm' -and -not -name *.src.rpm > output/tocheck
fail_names=()
while read f; do
	name="`rpm --qf '%{name}\n' -qp $f`"
	if [ "$name" != "${name%debugsource}" -o "$name" != "${name%debuginfo}"  ]; then
		continue
	fi
	echo -n "checking $f ... "
	check "$name" "$f" > output/$name.out || true
	sed -i "s/^$name\.[^:]\+: /$name: /" output/$name.out
	if diff -u tests/$name.ref output/$name.out; then
		echo "ok"
		: $((++good))
	else
		echo "fail"
		if [ ! -e tests/$name.ref ]; then
			echo "ref file missing."
			echo "you may want to copy the following to tests/$name.ref:"
			echo '++++'
			cat output/$name.out
			echo '++++'
		fi
		: $((++failed))
		fail_names+=($name)
	fi
done < output/tocheck
echo "good: $good, failed: $failed"
[ -z "$fail_names" ] || echo "failed tests: ${fail_names[@]}"
[ "$failed" = 0 ]
