#!/bin/bash

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

if [ -f /usr/libexec/helper-scripts/pre.bsh ]; then
   source /usr/libexec/helper-scripts/pre.bsh
fi

source /usr/share/debconf/confmodule

set -e

## Not set by DPKG for '.config' script.
DPKG_MAINTSCRIPT_PACKAGE="security-misc-shared"
DPKG_MAINTSCRIPT_NAME="config"

true "
#####################################################################
## INFO: BEGIN: $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $*
#####################################################################
"

## NOTE: Code duplication.
## Copied from: helper-scripts /usr/libexec/helper-scripts/package_installed_check.sh
##
## '.config' scripts are run very early. Even 'Pre-Depends: helper-scripts' would be insufficient.
## Therefore the code is duplicated here.
pkg_installed() {
   local package_name dpkg_query_output
   local requested_action status error_state

   package_name="$1"
   ## Cannot use '&>' because it is a bashism.
   dpkg_query_output="$(dpkg-query --show --showformat='${Status}' "$package_name" 2>/dev/null)" || true
   ## dpkg_query_output Examples:
   ## install ok half-configured
   ## install ok installed

   requested_action=$(printf '%s' "$dpkg_query_output" | awk '{print $1}')
   status=$(printf '%s' "$dpkg_query_output" | awk '{print $2}')
   error_state=$(printf '%s' "$dpkg_query_output" | awk '{print $3}')

   if [ "$requested_action" = 'install' ]; then
      true "$0: INFO: $package_name is installed, ok."
      return 0
   fi

   true "$0: INFO: $package_name is not installed, ok."
   return 1
}

check_migrate_permission_hardener_state() {
   local pkg_list modified_pkg_data_str custom_hardening_arr config_file

   ## If folder /var/lib/permission-hardener (version 1) does not exist, this migration is unneeded.
   if [ ! -d '/var/lib/permission-hardener' ]; then
      return 0
   fi

   local orig_hardening_arr custom_hardening_arr config_file custom_config_file
   if [ -f "/var/lib/security-misc/do_once/${FUNCNAME[0]}_version_2" ]; then
     return 0
   fi
   mkdir --parents '/var/lib/security-misc/do_once'

   orig_hardening_arr=(
      '/usr/lib/permission-hardener.d/25_default_passwd.conf'
      '/usr/lib/permission-hardener.d/25_default_sudo.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_bubblewrap.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_chromium.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_dbus.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_firejail.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_fuse.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_hardened_malloc.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_mount.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_pam.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_passwd.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_policykit.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_postfix.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_qubes.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_selinux.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_spice.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_ssh.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_sudo.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_unix_chkpwd.conf'
      '/usr/lib/permission-hardener.d/25_default_whitelist_virtualbox.conf'
      '/usr/lib/permission-hardener.d/20_user-sysmaint-split.conf'
      '/usr/lib/permission-hardener.d/30_ping.conf'
      '/usr/lib/permission-hardener.d/30_default.conf'
      '/etc/permission-hardener.d/25_default_passwd.conf'
      '/etc/permission-hardener.d/25_default_sudo.conf'
      '/etc/permission-hardener.d/25_default_whitelist_bubblewrap.conf'
      '/etc/permission-hardener.d/25_default_whitelist_chromium.conf'
      '/etc/permission-hardener.d/25_default_whitelist_dbus.conf'
      '/etc/permission-hardener.d/25_default_whitelist_firejail.conf'
      '/etc/permission-hardener.d/25_default_whitelist_fuse.conf'
      '/etc/permission-hardener.d/25_default_whitelist_hardened_malloc.conf'
      '/etc/permission-hardener.d/25_default_whitelist_mount.conf'
      '/etc/permission-hardener.d/25_default_whitelist_pam.conf'
      '/etc/permission-hardener.d/25_default_whitelist_passwd.conf'
      '/etc/permission-hardener.d/25_default_whitelist_policykit.conf'
      '/etc/permission-hardener.d/25_default_whitelist_postfix.conf'
      '/etc/permission-hardener.d/25_default_whitelist_qubes.conf'
      '/etc/permission-hardener.d/25_default_whitelist_selinux.conf'
      '/etc/permission-hardener.d/25_default_whitelist_spice.conf'
      '/etc/permission-hardener.d/25_default_whitelist_ssh.conf'
      '/etc/permission-hardener.d/25_default_whitelist_sudo.conf'
      '/etc/permission-hardener.d/25_default_whitelist_unix_chkpwd.conf'
      '/etc/permission-hardener.d/25_default_whitelist_virtualbox.conf'
      '/etc/permission-hardener.d/20_user-sysmaint-split.conf'
      '/etc/permission-hardener.d/30_ping.conf'
      '/etc/permission-hardener.d/30_default.conf'
   )

   pkg_list=( "security-misc-shared" )
   if pkg_installed user-sysmaint-split ; then
      pkg_list+=( "user-sysmaint-split" )
   fi
   if pkg_installed anon-apps-config ; then
      pkg_list+=( "anon-apps-config" )
   fi

   ## This will exit non-zero if some of the packages don't exist, but we
   ## don't care. The packages that *are* installed will still be scanned.
   modified_pkg_data_str="$(dpkg --verify "${pkg_list[@]}")" || true

   ## Example modified_pkg_data_str:
   #modified_pkg_data_str='missing     /usr/lib/permission-hardener.d/20_user-sysmaint-split.conf'

   readarray -t custom_hardening_arr < <(awk '/permission-hardener.d/{ print $NF }' <<< "${modified_pkg_data_str}")

   ## If the above `dpkg --verify` command doesn't return any permission-hardener
   ## related lines, the array will contain no meaningful info, just a single
   ## blank element at the start. Set the array to be explicitly empty in
   ## this scenario.
   if [ -z "${custom_hardening_arr[0]}" ]; then
      custom_hardening_arr=()
   fi

   for config_file in \
      /usr/lib/permission-hardener.d/*.conf \
      /etc/permission-hardener.d/*.conf \
      /usr/local/etc/permission-hardener.d/*.conf \
      /etc/permission-hardening.d/*.conf \
      /usr/local/etc/permission-hardening.d/*.conf
   do
      # shellcheck disable=SC2076
      if ! [[ " ${orig_hardening_arr[*]} " =~ " ${config_file} " ]]; then
         if [ -f "${config_file}" ]; then
            custom_hardening_arr+=( "${config_file}" )
         fi
      fi
   done

   if [ "${#custom_hardening_arr[@]}" != '0' ]; then
      for custom_config_file in "${custom_hardening_arr[@]}"; do
         if ! test -e "${custom_config_file}" ; then
            echo "$0: INFO: Possible missing configuration file found: '${custom_config_file}'"
         else
            echo "$0: INFO: Possible custom configuration file found: '${custom_config_file}'"
         fi
      done
      ## db_input will return code 30 if the message won't be displayed, which
      ## causes a non-interactive install to error out if you don't use || true
      db_input critical security-misc-shared/alert-on-permission-hardener-v2-upgrade || true
      ## db_go can return code 30 too in some instances, we don't care here
      # shellcheck disable=SC2119
      db_go || true
   fi

   touch "/var/lib/security-misc/do_once/${FUNCNAME[0]}_version_2"
}

check_migrate_permission_hardener_state

true "INFO: debhelper beginning here."

#DEBHELPER#

true "INFO: Done with debhelper."

true "
#####################################################################
## INFO: END  : $DPKG_MAINTSCRIPT_PACKAGE $DPKG_MAINTSCRIPT_NAME $*
#####################################################################
"

## Explicitly "exit 0", so eventually trapped errors can be ignored.
exit 0
