#!/bin/bash

# Define the patch content using cat command
UNIX_CHKPWD_PATCH=$(cat << 'EOF'
--- /etc/apparmor.d/unix-chkpwd 2024-10-07 13:41:33.143303700 -0600
+++ /etc/apparmor.d/unix-chkpwd 2024-10-07 13:36:55.740827834 -0600
@@ -11,7 +11,7 @@
 
 include <tunables/global>
 
-profile unix-chkpwd /{,usr/}{,s}bin/unix_chkpwd {
+profile unix-chkpwd /{,usr/}{,s}bin/unix_chkpwd flags=(attach_disconnected) {
   include <abstractions/base>
   include <abstractions/nameservice>
 
EOF
)
LIBREOFFICE_PATCH=$(cat << 'EOF'
--- /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin	2024-09-02 07:51:12.000000000 -0600
+++ /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin	2024-10-24 09:52:51.062702354 -0600
@@ -76,7 +76,7 @@

 #include <tunables/global>

-profile libreoffice-soffice /usr/lib/libreoffice/program/soffice.bin flags=(complain) {
+profile libreoffice-soffice /usr/lib/libreoffice/program/soffice.bin flags=(complain,attach_disconnected) {
   #include <abstractions/private-files>

   #include <abstractions/audio>
EOF
)

# Check if the file /etc/apparmor.d/unix-chkpwd exists
if [[ -f /etc/apparmor.d/unix-chkpwd ]]; then
    # Idempotent, non-interactive: only reverse if our change is present
    if grep -q 'flags=(attach_disconnected)' /etc/apparmor.d/unix-chkpwd; then
        echo "$UNIX_CHKPWD_PATCH" | patch --batch --fuzz 2 --silent --reverse -p0 /etc/apparmor.d/unix-chkpwd >/dev/null 2>&1 || true
        apparmor_parser -r /etc/apparmor.d/unix-chkpwd >/dev/null 2>&1 || true
    fi
fi

# Check if the file /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin exists
if [[ -f /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin ]]; then
    # Idempotent, non-interactive: only reverse if our change is present
    if grep -q 'attach_disconnected' /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin; then
        echo "$LIBREOFFICE_PATCH" | patch --batch --fuzz 2 --silent --reverse -p0 /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin >/dev/null 2>&1 || true
        apparmor_parser -r /etc/apparmor.d/usr.lib.libreoffice.program.soffice.bin >/dev/null 2>&1 || true
    fi
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update
