#!/bin/sh
#
# © Microsoft Corporation. All rights reserved.
#
# The prerm script is invoked before a package version's files are
# removed in various situations. In the general case, we always want to
# try to stop running services so binaries can be replaced. Additionally,
# if the package is being completely removed, we also try to clean up
# per-user data - the postrm stage is too late for this, because we rely
# on information in the agent unit files to do this (and therefore cannot
# list them in Debian's conffiles)

set -e

if [ -z "${DPKG_ROOT:-}" ] && [ -d /run/systemd/users ]; then
    # deb-systemd-invoke recently gained support for talking to the user session manager
    if dpkg --compare-versions "$(dpkg-query --show --showformat='${Version}' init-system-helpers)" ge 1.61~; then
        deb-systemd-invoke --user stop intune-agent.timer intune-agent.service >/dev/null || true
    else
        pkill -TERM intune-agent >/dev/null || true
    fi

    # Only if the package is being completely removed (dpkg --remove, apt remove, etc.)
    # should we attempt to clean user data
    if [ "$1" = "remove" ]; then
        # Remove Intune's PAM configuration profile
        pam-auth-update --package --remove intune >/dev/null || true

        # systemd 249.10 added APIs to reach all user instances from root, but debhelper does not support cleaning yet.
        # Instead, try to enumerate all of the active user units and ask them to clean state directly
        if dpkg --compare-versions "$(systemctl --version --quiet | sed -n -r "s/systemd ([0-9]+) \\(.*/\1/p")" ge 249; then
            for instance in $(systemctl --no-legend --quiet list-units 'user@*' | sed -n -r 's/.*user@([0-9]+).service.*/\1/p'); do
               systemctl --quiet --user --machine "${instance}@" clean --what=state --what=configuration --what=runtime intune-agent.service >/dev/null || true
            done
        else
            echo "Current systemd version does not support automated cleanup of user instances, please remove ~/.config/intune/ manually to cleanup leftover state."
        fi

        deb-systemd-invoke stop 'intune-daemon.service' 'intune-daemon.socket' >/dev/null || true

        # Ensure all tmpfiles are removed now that the services touching them
        # are stopped
        if [ -d /run/systemd/system ] ; then
            systemd-tmpfiles --remove intune.conf >/dev/null || true
        fi
    fi
fi
