#!/bin/bash
aptdir="/var/univention/buildsystem2/apt/ucs_4.3-0"

cleanup() {
	rm -rf "${wd:?Workdir missing}"
}
trap cleanup EXIT
wd=$(mktemp -d)
rm sources.log

compare_debian_sources_against_ucs() {
	local debian_srclstgz
	local ucs_srclst
	debian_srclstgz="$1"
	ucs_srclst="$2"

	while read -d $'\0' rec; do
		section=$(sed -n 's/^Section: //p' <<<"$rec")
		if [ "$section" = "games" ]; then
			continue
		fi
		
		extra_source_only=$(sed -n 's/^Extra-Source-Only: //p' <<<"$rec")
		if [ "$extra_source_only" = "yes" ]; then
			continue
		fi
		
		srcpkg=$(sed -n 's/^Package: //p' <<<"$rec")

		ucsrec=$(grep-dctrl -r -F Package -s "Package,Binary,Version" "^$srcpkg$" "$ucs_srclst")
		if [ -z "$ucsrec" ]; then
			continue
		fi
		ucsver=($(sed -n 's/^Version: //p' <<<"$ucsrec" | sort -r))
		ucsver="${ucsver[0]}"
		debver=$(sed -n 's/^Version: //p' <<<"$rec")

		statusline="$srcpkg:\t$ucsver\t$debver"
		if dpkg --compare-versions "$ucsver" lt "$debver"; then
			statusline="ERROR: $statusline"
			echo -e "$statusline"
		fi
		echo -e "$statusline" >> sources.log

		continue

		binpkg=$(sed -n 's/^Binary: //p' <<<"$rec")
		if [ -n "$binpkg" ]; then
			IFS=", " binpkg=($binpkg)
		else
			binpkg="$srcpkg"
		fi
	done < <(zcat "$debian_srclstgz" \
		| grep-dctrl -r -s "Package,Binary,Version,Section,Extra-Source-Only" -F Package "^.*" \
		| sed -e 's/^$/\x00/')
}

dist=stretch

for distchannel in \
	"debian/dists/$dist" \
	"debian-security/dists/$dist/updates"
do
	for distsection in main contrib non-free;
	do
		srclsturl="http://ftp.de.debian.org/$distchannel/$distsection/source/Sources.gz"
		wget -P "$wd" "$srclsturl" || exit 1
		echo -e "## Checking $distchannel/$distsection" >> sources.log
		compare_debian_sources_against_ucs "$wd/Sources.gz" "$aptdir/source/Sources"
		rm -f "$wd/Sources.gz"
	done
done
