#!/bin/bash
# Filename:      ${GRML_FAI_CONFIG}/config/scripts/GRMLBASE/01-packages
# Purpose:       check for packages that have been requested but could not be installed
# Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2 or any later version.
################################################################################

set -u
set -e

echo -n > "${LOGDIR}"/package_errors.log  # ensure we start with an empty file

if ! [ -e "${LOGDIR}"/software.log ] ; then
  echo "Warning: no ${LOGDIR}/software.log found (build/update run?), skipping check for unknown packages."
else
  if grep -q 'These unknown packages' "${LOGDIR}"/software.log ; then
    echo "Identified unknown packages in ${LOGDIR}/software.log"
    grep 'These unknown packages' "${LOGDIR}"/software.log | \
      sed 's/.*These unknown packages.*: //; s/ / not_installable\n/g' >> "${LOGDIR}/package_errors.log"
  fi
fi

PACKAGE_LIST=/var/log/install_packages.list
# shellcheck disable=SC2154
if ! [ -r "${target}/${PACKAGE_LIST}" ] ; then
  echo "No ${target}/${PACKAGE_LIST} found, will not run package validation check."
else
  echo "Validating package list against dpkg state..."

  TMPSTDOUT=$(mktemp)
  TMPSTDERR=$(mktemp)

  # 1) catch packages that aren't in state 'ii' (marked for installation
  # and successfully instead) on stdout
  # 2) catch error messages like 'dpkg-query: no packages found matching $package"
  # for packages unknown to dpkg on stderr
  # NOTE: 'grep -v -- '-$' ignores packages in FAI's package list that are
  # marked for removal
  # shellcheck disable=SC2046
  ${ROOTCMD} dpkg --list $(grep -v '^#' "${target}/${PACKAGE_LIST}" | grep -v -- '-$') 2>"${TMPSTDERR}" | \
    grep -e '^[urph][ncufhWt]' > "${TMPSTDOUT}" || true

  # extract packages from stdout
  awk '/^un/ {print $2 " not_installable"}' "${TMPSTDOUT}" >> "${LOGDIR}/package_errors.log"

  # extract packages from stderr
  grep 'packages found matching' "${TMPSTDERR}" | \
    sed 's/dpkg-query: [Nn]o packages found matching \(.*\)/\1 not_installable/' >> "${LOGDIR}/package_errors.log"

  rm -f "${TMPSTDOUT}" "${TMPSTDERR}"
fi

if [ -s "${LOGDIR}/package_errors.log" ] ; then
  echo "Warning: failed (there have been errors, find them at ${LOGDIR}/package_errors.log)."
else
  echo "Done - no errors found."
fi

## END OF FILE #################################################################
# vim:ft=sh expandtab ai tw=80 tabstop=4 shiftwidth=2
