#!/bin/bash

## Copyright (C) 2019 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AppArmor profiles in live mode need the following line to work
## but because of a bug in AppArmor, this breaks reloading profiles
## so it is only enabled in live mode.
## https://forums.whonix.org/t/error-values-added-to-a-non-existing-variable-homedirs-rw-home-in-tunables-home-d-live-mode/8065
## https://forums.whonix.org/t/live-mode-etc-apparmor-d-tunables-home-d-live-mode-breaks-aa-enforce/5868
## https://bugs.launchpad.net/apparmor/+bug/1331856
## https://bugs.launchpad.net/apparmor/+bug/1387775

set -x
set -e

if grep "boot=live" /proc/cmdline ; then
   ## Live Mode.

   ## Idempotence.
   ## Allow to disable this feature by using double hash ('##').
   if grep "^#@{HOMEDIRS}+=/rw/home/" /etc/apparmor.d/tunables/home.d/live-mode ; then
      LANG=C str_replace "#@{HOMEDIRS}+=/rw/home/" "@{HOMEDIRS}+=/rw/home/" /etc/apparmor.d/tunables/home.d/live-mode
   fi
else
   ## Persistent Mode.

   ## Idempotence.
   ## grep to see if it is enabled (not commented out) before str_replace
   ## adding a hash ('#') in front of it to avoid adding multiple hashes in
   ## front of it.
   if grep "^@{HOMEDIRS}+=/rw/home/" /etc/apparmor.d/tunables/home.d/live-mode ; then
      LANG=C str_replace "@{HOMEDIRS}+=/rw/home/" "#@{HOMEDIRS}+=/rw/home/" /etc/apparmor.d/tunables/home.d/live-mode
   fi
fi
