#!/bin/sh
### This lib is supposed to export a set of functions that will print out the
### pkg list, in their versions and a pool path to download the .md5 files.

. /lib/system-integrity-check/envinfo

# this is the only info on the system we need to rely for now.
# later we might implement a print_pkg_list_from_contents.
print_pkg_list_from_status() {

  if [ ! -r ${TOPDIR}/var/lib/dpkg/status ]; then
    return 1
  fi

  chroot ${TOPDIR} dpkg-query -f'${Status}\n${Package} ${Version}\n' -W > /var/cache/system-integrity-check/pkglist

  rm -f /var/cache/system-integrity-check/pkglist.tmp

  while read status <&8; do
    read line <&8
    case "$status" in
      "install ok installed")
         echo "$line" >> /var/cache/system-integrity-check/pkglist.tmp
      ;;
      *)
         # hook to handle pkgs that are not in installed state.
         # deinstall ok config-files seems common.
      ;;
    esac
  done 8</var/cache/system-integrity-check/pkglist

  mv /var/cache/system-integrity-check/pkglist.tmp /var/cache/system-integrity-check/pkglist

  return 0

}

# given pkg name and version return the associated pool filename.
# $1 pkgname
# $2 version:
#             Version might contain an epoch. epoch is not
#             reflected in the pkg name in the pool so kill it.
#             Version might contain a +. This needs escaping for grep
#             otherwise there is no match.
print_pool() {
  version=$(echo "$2" | sed -e 's#^[[:digit:]]*:##' -e 's#+#\\+#g' -e 's#-#\\-#g')
  pkgname=$(echo "$1" | sed -e 's#+#\\+#g' -e 's#-#\\-#g')
  poolname=$(grep -E /${pkgname}_${version}_'('$arch'|all)' /var/cache/system-integrity-check/Packages | head -n 1)
}
