#!/bin/bash -e
# Check Checksums
# Christoph Lameter <clameter@debian.org> Feb 9, 1997

function checksum() {
	cd /
	if [ -f $1conffiles -a "$C_ALL" = "" ]; then
		CF=`cat $1conffiles|colrm 1 1`
		grep -Fv "$CF" <$1md5sums | md5sum -c$VOPT 2>&1 || RC=1
	else
		md5sum -c$VOPT $1md5sums 2>&1 || RC=1
	fi
}

if [ "$1" = "-a" ]; then
	C_ALL=1
	shift
fi

RC=0
VOPT="v"
if [ "$1" = "-s" ]; then
	VOPT=""
	shift
fi

if [ "$1" = "" ]; then
	for i in /var/lib/dpkg/info/*.md5sums; do
		if [ "$VOPT" ]; then
			echo "-- Checksums from $i"
		fi
		checksum `expr $i : "\(.*\.\).*"` || echo "Checking against $i failed"
	done
fi

for i in $*; do
        if expr "$i" : ".*\.deb" >/dev/null; then
                if [ -f $i ]; then
                        mkdir /tmp/$$
                        dpkg-deb --control $i /tmp/$$
                        if [ -f /tmp/$$/md5sums ]; then
				checksum /tmp/$$/
                        else
                                echo "Package $i has no checksums file"
				rm -rf /tmp/$$
                                exit 1
                        fi
                        rm -rf /tmp/$$
                        exit 0
                else
                        echo "Package $i not found"
                        exit 1
                fi
        else
		F=/var/lib/dpkg/info/$i
		if [ -f $F.md5sums ]; then
			checksum $F.
		else
			echo "Package $i did not come with checksums"
		fi
	fi
done

exit $RC
