# Hook for the postrm maintscript of any virt package
# in order to manage base/HWE stacks

# purge
#
# HWE and base packages share the same conffiles. Static conffiles are tracked
# by dpkg and handled correctly across the hwe/base lifecycle because the two
# packages Replaces each other. Dynamic conffiles (systemd symlinks, drop-in
# configs, ...) are instead managed by the package itself or by helpers
# (systemd, init, apparmor, ...) that are unaware of the base<->hwe
# relationship. As a result, purging one package while its counterpart is
# still installed can break the counterpart.
#
# To avoid this, skip the purge whenever the counterpart is still present.
if [ "$1" = "purge" ]; then
  case "$DPKG_MAINTSCRIPT_PACKAGE" in
    *-hwe) counterpart="${DPKG_MAINTSCRIPT_PACKAGE%-hwe}" ;;
    *)     counterpart="${DPKG_MAINTSCRIPT_PACKAGE}-hwe" ;;
  esac

  if status="$(dpkg-query -f='${db:Status-Status}' -W "$counterpart" 2>/dev/null)"; then
    # Skip purge if the counterpart package still has files on disk (any non-removed state).
    skip_purge=0
        case "$status" in
      not-installed)
        # counterpart is not installed, safe to purge
        ;;
      config-files)
        # counterpart is removed and waiting for purge, only config files left, safe to purge
        ;;
      installed)
        # counterpart is still installed, skip purge
        skip_purge=1
        ;;
      unpacked)
        # counterpart is unpacked, skip purge
        skip_purge=1
        ;;
      half-installed)
        # counterpart is half-installed, skip purge
        skip_purge=1
        ;;
      half-configured)
        # counterpart is half-configured, skip purge
        skip_purge=1
        ;;
      triggers-awaited)
        # counterpart is waiting for triggers, skip purge
        skip_purge=1
        ;;
      triggers-pending)
        # counterpart is waiting for triggers, skip purge
        skip_purge=1
        ;;
      *)
        # Unknown state: be conservative and skip purge.
        skip_purge=1
        ;;
    esac

    if [ "$skip_purge" -eq 1 ]; then
      echo "Counterpart package $counterpart is still present, skipping purge of $DPKG_MAINTSCRIPT_PACKAGE"
      exit 0
    fi
  fi
fi
