# Borrowed from Debian.
_systemctl() {
	if [ -z "$DPKG_ROOT" ] && [ -d /run/systemd/system ]; then
		systemctl "$@"
	fi
}

_update_binfmt() {
    if [ "$(_systemctl show -P LoadState systemd-binfmt.service)" != "masked" ]; then
        # Note: try-restart doesn't restart inactive services
        echo "Reloading binfmt ..."
        _systemctl restart systemd-binfmt.service || true
    fi
}

_reload_daemon() {
    echo "Reloading systemd manager configuration ..."
    _systemctl --system daemon-reload || true
}

# Add `|| true' just to be safe, but this shouldn't be needed unless
# the package upgrade sequence is messed up (i.e., whilst updating
# OpenSSL, breaking systemd programs).
_systemctl daemon-reexec || true
# https://src.fedoraproject.org/rpms/systemd/blob/fc47a92e4a3828d6b3fc7901b481135a87132cd7/f/systemd.spec#_1103
/usr/lib/systemd/systemd-update-helper user-reexec || true

systemd-machine-id-setup ${DPKG_ROOT:+--root="$DPKG_ROOT"}

setfacl -Rnm g:wheel:rx,d:g:wheel:rx,g:adm:rx,d:g:adm:rx \
	"${DPKG_ROOT}"/var/log/journal/ 2>/dev/null

systemd-sysusers ${DPKG_ROOT:+--root="$DPKG_ROOT"}
# NOTE: systemd-hwdb is not available on Afterglow.
if command -v systemd-hwdb &>/dev/null ; then
	systemd-hwdb ${DPKG_ROOT:+--root="$DPKG_ROOT"} update
fi
journalctl ${DPKG_ROOT:+--root="$DPKG_ROOT"} --update-catalog

if [ ! -d /var/log/journal/remote ]; then
	mkdir -m2755 "${DPKG_ROOT}"/var/log/journal/remote
fi
chgrp systemd-journal-remote "${DPKG_ROOT}"/var/log/journal/remote

if grep -q "$(sha1sum "${DPKG_ROOT}"/etc/machine-id | cut -d ' ' -f 1)" \
	/usr/share/doc/systemd/aosc-revoked-machine-ids; then
	echo "Your machine-id seems to be non-unique, a new one will be generated."
	echo "Please reboot your system after this update."
	rm /etc/machine-id
	ln -sfv /etc/machine-id /var/lib/dbus/machine-id
	systemd-machine-id-setup ${DPKG_ROOT:+--root="$DPKG_ROOT"}
fi

# Systemd's forced seduction.
getent group nobody > /dev/null && groupdel nobody
getent group systemd-nogroup > /dev/null || \
	groupadd -g 65534 systemd-nogroup > /dev/null
getent passwd systemd-nobody > /dev/null || \
	useradd -u 65534 -g systemd-nogroup -d /dev/null -s /bin/false \
		-c 'Unprivileged User (systemd)' systemd-nobody > /dev/null

if [ "$1" = "triggered" ]; then
    shift

    # Note: avoid duplicate trigger actions.
    # e.g. postinst triggered /usr/lib/binfmt.d systemd-binfmt
    update_binfmt=0
    reload_daemon=0

    for trigger in $@; do
        case $trigger in
            /etc/binfmt.d|/usr/lib/binfmt.d|systemd-binfmt)
                update_binfmt=1
                ;;
            /etc/systemd/system|/usr/lib/systemd/system|daemon-reload)
                reload_daemon=1
                ;;
        esac
    done

    [ "$update_binfmt" = 1 ] && _update_binfmt
    [ "$reload_daemon" = 1 ] && _reload_daemon

    exit 0
fi
