#!/bin/bash

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

set -x
set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

unexpected_key_file() {
   error "ERROR: unexpected key file found!"
   exit 1
}

own_filename="$(basename -- "${BASH_SOURCE[0]}")"
for skip_script in ${SKIP_SCRIPTS-}; do
   if [ "$skip_script" = "$own_filename" ]; then
      true "INFO: Skipping $own_filename, because SKIP_SCRIPTS includes it."
      exit 0
   fi
done
unset skip_script

## dpkg --audit does not return anything, if everything is fine.
## Therefore we see if dpkg has to say something, and if yes, the system is
## broken and we abort.
dpkg_audit_output="$(dpkg --audit 2>&1)"
if [ ! "$dpkg_audit_output" = "" ]; then
   error "dpkg_audit_output not empty!"
fi

dpkg --configure -a

## Disabled. Trixie no longer ships sysctl.conf, but sysctl -p assumes
## sysctl.conf exists. The file was entirely commented out anyway, so this was
## little more than a no-op.
#sysctl -p

DEBIAN_FRONTEND=noninteractive dpkg-reconfigure tzdata

debsums_output_1="$(debsums --list-missing 2>&1)"

if [ "$debsums_output_1" = "" ]; then
   true "INFO: Ok, no packages (or debs) with missing MD5 sums file found."
else
   error "ERROR: Packages (or debs) with missing MD5 sums file found!"
fi

debsums --silent || true

# debsums: missing file /lib/modules/4.19.0-4-amd64/kernel/drivers/staging/vboxvideo/vboxvideo.ko (from linux-image-4.19.0-4-amd64 package)
# debsums: missing file /lib/modules/4.19.0-4-amd64/kernel/drivers/virt/vboxguest/vboxguest.ko (from linux-image-4.19.0-4-amd64 package)

# if [ ! "$exit_code" = "0" ]; then
#    error "ERROR: debsums returned a non-zero exit_code: $exit_code!"
# fi
#
# if [ "$debsums_output_2" = "" ]; then
#    true "INFO: Ok, no packages (or debs) with missing files file found."
# else
#    error "ERROR: Packages (or debs) with missing files found!"
# fi

true "INFO: Listing changed configuration files..."
true "      (Only an information, no check...)"
true "      (Has to be reviewed manually by the builder.)"
true "      (A differencing /etc/resolv.conf.whonix is expected when building \
Virtual Machine images, because the /etc/resolv.conf from the host has been mounted inside the image.)"

debsums --config --silent 2>&1 || true

true "INFO: Listed changed configuration files."

## Provided by package: 'helper-scripts'
# shellcheck source=/usr/sbin/shim-signed-mok-setup
source /usr/sbin/shim-signed-mok-setup
## sets: 'dkms_mok_*' variables
dkms_mok_variables_set

! test -e "${dkms_mok_public_file}" || unexpected_key_file
! test -e "${dkms_mok_private_file}" || unexpected_key_file
! test -e "${shim_mok_public_file}" || unexpected_key_file
! test -e "${shim_mok_private_file}" || unexpected_key_file
