#!/bin/bash

set -e

pathname="$1"
checksum="$2"

deb_checksum="$(dpkg-query -f "\${Conffiles}\n" -W | \
                awk -v pathname="${pathname}" \
                  '$1 == pathname && $3 != "obsolete" { print $2 }')"
if [ -e "${pathname}" ]; then
  sys_checksum="$(md5sum "${pathname}" | cut -f1 -d\ )"
fi

if [ "${deb_checksum}" = "${checksum}" ] &&
   [ "${sys_checksum}" = "${checksum}" ]; then
  # If current installed file matches the checksum on the dpkg database and
  # of the filesystem object, we can leave it as is.
  echo "Info: ${pathname} installed checksum matches, skipping"
elif [ -z "${deb_checksum}" ]; then
  if [ -n "${sys_checksum}" ]; then
    # If the file exists and is not tracked anymore by dpkg, we remove it as
    # it stopped being shipped in a package.
    echo "Info: ${pathname} file not tracked, removing"
    rm -f "${pathname}"
  fi
else
  # XXX: Otherwise if it does not match the checksums, we remove it, to get
  # a consitent state. Ideally we would restore the shipped file here.
  if [ -n "${sys_checksum}" ]; then
    echo "Warn: ${pathname} installed checksum differs (present), removing" >&2
    rm -f "${pathname}"
  else
    echo "Warn: ${pathname} installed checksum differs (missing), ignoring" >&2
  fi
fi
