#!/bin/sh

set -e

# summary of how this script can be called:
#
#   * <postinst> `configure' <most-recently-configured-version>
#   * <old-postinst> `abort-upgrade' <new-version>
#   * <conflictor's-postinst> `abort-remove' `in-favour' <package> <new-version>
#   * <postinst> `abort-remove'
#   * <deconfigured's-postinst> `abort-deconfigure' `in-favour' <failed-install-package>
#     <version> `removing' <conflicting-package> <version>
#
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

case "$1" in
    configure)
        if [ -z "$2" ]; then
            adduser --quiet \
                    --system \
                    --group \
                    --disabled-login \
                    --home /nonexistent \
                    --no-create-home \
                    --gecos "libvirt-dbus user" \
                    libvirtdbus
        fi

        # Debian, like upstream, uses polkit to control access to libvirt:
        # specifically, /run/libvirt/libvirt-sock has ownership root:root and
        # permissions 666, but the policy defined in
        # /usr/share/polkit-1/rules.d/libvirt-dbus.rules prevents users other
        # than those in the libvirt group to actually perform management
        # operations.
        #
        # Ubuntu doesn't use polkit for this, and relies on standard Unix
        # permissions instead: specifically, the socket has ownership
        # root:libvirt and permissions 660.
        #
        # The end result is the same, in that only root and users that are in
        # the libvirt group can perform privileged operations.
        #
        # For libvirt-dbus to work, the libvirtdbus user that the daemon runs
        # as needs to be able to open a privileged connection to libvirt.
        #
        # Once again, Debian achieves this through polkit by installing a
        # special rule, whereas Ubuntu needs to add the user to the libvirt
        # group, which is what we do here. Note that the user is only added to
        # the group on fresh installs or upgrades from old versions of
        # libvirt-dbus, because we don't want to accidentally override local
        # changes to group membership.
        if [ -z "$2" ] || dpkg --compare-versions -- "$2" lt "1.4.1-1"; then
            if grep -qs 'ubuntu' /etc/os-release || grep -qs ubuntu /usr/lib/os-release; then
                if getent group libvirt >/dev/null 2>&1; then
                    adduser libvirtdbus libvirt
                fi
            fi
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#

exit 0
