#!/bin/bash

dpkg-query -W -f='${Package}\t${Version}\n' | while read l
do
  pkg=$(echo "$l" | cut -f1)
  if [ -f "/var/lib/dpkg/info/${pkg}:amd64.md5sums" ]
  then
    result="$(cd /; nice -n 19 ionice -c 3 md5sum --quiet -c /var/lib/dpkg/info/${pkg}:amd64.md5sums 2>&1)"
  else
    result="$(cd /; nice -n 19 ionice -c 3 md5sum --quiet -c /var/lib/dpkg/info/${pkg}.md5sums 2>&1)"
  fi
  if [ "$?" -ne 0 ]
  then
    #exclude packages for which we cannot verify md5sum, no md5sums file
    if [ "$(echo "$result" | grep md5sums | grep -c 'No such file')" -gt 0 ]
    then
      continue
    fi

    #exclude ./etc (elasticsearch packaging issue)
    result="$(echo "$result" | grep -v '^\./etc/')"

    #exclude .pyc files
    result="$(echo "$result" | grep -v '\.pyc$')"

    #exclude bad formatted / empty md5sum files and md5sum summary lines
    result="$(echo "$result" | grep -v 'did NOT match\|md5sum: ')"
    if [ -n "$result" ]
    then
      echo -e "$result" | sed "s|^|$l\t|"
    fi
  fi
done
