#!/bin/sh
# postinst script for gnome-remote-desktop
# inspired by polkitd.postinst
#
# This can be dropped if https://bugs.debian.org/1070473 gets fixed
#
# see: dh_installdeb(1)

set -e

case "$1" in
    configure)
        if ! getent passwd gnome-remote-desktop >/dev/null; then
            user_changed=yes
        else
            user_changed=
        fi

        # Intentionally not using dh_installsysusers: we need enough control
        # over sequencing to reload dbus-daemon after doing this, but before
        # restarting gnome-remote-desktop
        if command -v systemd-sysusers >/dev/null; then
            systemd-sysusers ${DPKG_ROOT:+--root="$DPKG_ROOT"} gnome-remote-desktop-sysusers.conf || true
        fi

        if command -v systemd-tmpfiles >/dev/null; then
            systemd-tmpfiles ${DPKG_ROOT:+--root="$DPKG_ROOT"} --create gnome-remote-desktop-tmpfiles.conf || true
        fi

        # If the gnome-remote-desktop user was newly created,
        # the dbus-daemon might not know about that until reloaded.
        # dbus-broker's service has a dbus.service alias, so this will reload
        # either dbus-daemon or dbus-broker, whichever is used.
        if [ -z "${DPKG_ROOT-}" ] && [ -n "$user_changed" ]; then
            invoke-rc.d dbus reload || true
        fi

	# 51~alpha-0ubuntu1 shipped d/p/data-Add-grd-user-to-tss-group.patch,
	# which added an "m gnome-remote-desktop tss" line to the sysusers
	# config. That made the TPM credentials backend reachable, which is
	# broken upstream (LP: #2164534).
	if [ -z "${DPKG_ROOT-}" ] \
	   && dpkg --compare-versions "$2" ge-nl 51~alpha-0ubuntu1 \
	   && dpkg --compare-versions "$2" lt-nl 51~alpha-0ubuntu2; then
		if id -nG gnome-remote-desktop 2>/dev/null | grep -qw tss; then
			printf "Removing gnome-remote-desktop from the tss group, see LP: #2164534\n"
			gpasswd -d gnome-remote-desktop tss >/dev/null || true
		fi
	fi

	# Disable the system service by default for users updating from a buggy version
	if dpkg --compare-versions "$2" lt-nl 48.1-1; then
		if deb-systemd-helper --quiet was-enabled 'gnome-remote-desktop.service'; then
			printf "Disable system unit that shouldn't have been auto enabled\n"
			deb-systemd-helper disable 'gnome-remote-desktop.service' >/dev/null || true
		fi
	fi
    ;;

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

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
