#!/bin/sh
set -eu

profile_source=/usr/share/apparmor/extra-profiles/bwrap-userns-restrict
profile_target=/etc/apparmor.d/bwrap-userns-restrict
profile_marker=/var/lib/afi/bwrap-profile-owned
restriction=/proc/sys/kernel/apparmor_restrict_unprivileged_userns

[ "${1:-}" = configure ] || exit 0
[ -r "$restriction" ] && [ "$(cat "$restriction")" = 1 ] || exit 0

if [ ! -f "$profile_source" ]; then
    printf '%s\n' 'afi: Bubblewrap AppArmor profile is unavailable; sandbox startup will refuse to run' >&2
    exit 0
fi

if [ ! -e "$profile_target" ] && [ ! -L "$profile_target" ]; then
    install -d -m 0755 /var/lib/afi
    ln -s "$profile_source" "$profile_target"
    : > "$profile_marker"
elif [ ! -f "$profile_marker" ]; then
    if [ ! -L "$profile_target" ] \
        || [ "$(readlink "$profile_target")" != "$profile_source" ]; then
        printf '%s\n' 'afi: preserving the existing Bubblewrap AppArmor profile' >&2
        exit 0
    fi
elif [ ! -L "$profile_target" ] \
    || [ "$(readlink "$profile_target")" != "$profile_source" ]; then
    rm -f "$profile_marker"
    printf '%s\n' 'afi: preserving the modified Bubblewrap AppArmor profile' >&2
    exit 0
fi

if ! /usr/sbin/apparmor_parser -r "$profile_target"; then
    printf '%s\n' 'afi: Bubblewrap AppArmor profile could not be loaded; sandbox startup will refuse to run' >&2
fi
