#!/bin/sh
set -e

is_installed()
{
	local pkg="$1"
	dpkg-query -s "$pkg" >/dev/null 2>&1 || return 1
	local status="$(dpkg-query -W -f '${Status}' $pkg)"
	test "$status" != "unknown ok not-installed" || return 1
	test "$status" != "deinstall ok config-files" || return 1
	return 0
}

# skip the md5sum check if /usr/share/doc is pruned
test ! -f /etc/dpkg/dpkg.cfg.d/piuparts-path-exclude || exit 0

for pkg in ${PIUPARTS_OBJECTS%%=*}
do
	# skip check if the package is not installed
	is_installed "$pkg" || continue

	md5file="/var/lib/dpkg/info/$pkg.md5sums"
	test -f "$md5file" || md5file="/var/lib/dpkg/info/$pkg:$(dpkg --print-architecture).md5sums"
	if [ ! -f "$md5file" ]; then
		echo "MD5SUM FILE NOT FOUND FOR $pkg"
		continue
	fi

	f1=/var/run/f1.$$
	sed -r 's%^[0-9a-f]{32}  %/%' "$md5file" | sort >$f1

	f2=/var/run/f2.$$
	>$f2
	dpkg -L "$pkg" | sed 's,\\,\\\\,g' | sort | \
	while read f ; do
		if [ "$f" != "${f#package diverts others to: }" ]; then
			: # skip diversion information
		elif [ "$f" != "${f#locally diverted to: }" ]; then
			: # skip diversion information
		elif [ -d "$f" ]; then
			: # ignore directories
		elif [ "$f" = "/home" ]; then
			: # ignore directory shipped by base-files that is
			  # turned into a file by our post_setup_forbid_home script
		elif [ -L "$f" ]; then
			: # ignore links
		elif [ -z "${f%%/etc/*}" ]; then
			: # ignore files in /etc - probably conffiles
		elif [ ! -e "$f" ]; then
			echo "${pkg}: MISSING OBJECT $f"
		else
			echo "$f" >> $f2
		fi
	done

	comm -13 $f1 $f2 | sed "s/^/${pkg}: FILE WITHOUT MD5SUM /"
	comm -23 $f1 $f2 | sed "s/^/${pkg}: MD5SUM WITHOUT FILE /"

	rm -f $f1 $f2
done
