#!/bin/sh
set -e

case "$1" in
    configure)
        # Create postallow system group and user if they don't exist
        if ! getent group postallow > /dev/null 2>&1; then
            addgroup --system postallow
        fi
        if ! getent passwd postallow > /dev/null 2>&1; then
            adduser --system --ingroup postallow \
                    --no-create-home \
                    --home /var/lib/postallow \
                    --shell /usr/sbin/nologin \
                    --gecos "Postallow allowlist generator" \
                    postallow
        fi
        # Create output directory owned by the postallow user
        install -d -o postallow -g postallow -m 755 /var/lib/postallow

        # Load AppArmor profile if AppArmor is active
        if command -v apparmor_parser > /dev/null 2>&1 && \
           [ -d /sys/kernel/security/apparmor ] && \
           [ -f /etc/apparmor.d/usr.bin.postallow ]; then
            # Upstream ships this profile as best-effort and not tested on a
            # live system. On first install, force complain mode, so that a
	    # bad rule can only be logged, never break postallow; the admin
	    # can promote it to enforce with aa-enforce(8) once satisfied.
	    # Leave upgrades alone so that we never override a mode the admin
	    # has set.
            if [ -z "$2" ]; then
                mkdir -p /etc/apparmor.d/force-complain
                ln -sf ../usr.bin.postallow \
                    /etc/apparmor.d/force-complain/usr.bin.postallow
            fi
            apparmor_parser -r /etc/apparmor.d/usr.bin.postallow || true
        fi
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
    *)
        echo "postinst called with unknown argument '$1'" >&2
        exit 1
        ;;
esac

#DEBHELPER#
exit 0
