#!/bin/sh

# SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: LGPL-3.0-or-later

#DEBHELPER#

# NOTE:
# Backport dh_installsystemduser features here to (re)start user level services here.
# This is needed until debhelper-compat 14.
instances="$(systemctl --no-legend --quiet list-units 'user@*' | sed -n -r 's/.*user@([0-9]+).service.*/\1/p')"
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ]; then
        if [ -z "${DPKG_ROOT:-}" ] && [ -d /run/systemd/system ]; then
                # Here we reload synchronously, as we really need to block in
                # order to ensure the following restart also works. Furthermore,
                # if there is no D-Bus user session, the restart won't work either,
                # so there's no point if falling back to signals - so either both
                # of these operations work, or both fail.

                # NOTE:
                # orgin script from postinst-systemd-user-restart
                # deb-systemd-invoke --user daemon-reload >/dev/null || true
                # deb-systemd-invoke --user restart #UNITFILES# >/dev/null || true

                for instance in $instances; do
                        systemctl --user --machine="$instance"@ daemon-reload >/dev/null || true
                done
                for instance in $instances; do
                        systemctl --user --machine="$instance"@ restart linglong-session-helper.service >/dev/null || true
                        systemctl --global --machine="${instance}"@ enable cn.org.linyaps.preloader.service > /dev/null || true
                done
        fi
fi

case "$1" in
configure)
        # enable kernel.unprivileged_userns_clone
        # disable kernel.apparmor_restrict_unprivileged_unconfined and kernel.apparmor_restrict_unprivileged_userns
        if [ -f /usr/lib/sysctl.d/linglong.conf ]; then
                sysctl -p /usr/lib/sysctl.d/linglong.conf 2>/dev/null || true
        fi
        ;;
abort-upgrade | abort-remove | abort-deconfigure) ;;
*)
        echo "postinst called with unknown argument '$1'" >&2
        exit 0
        ;;
esac

exit 0

# vi: ft=sh