#!/bin/bash

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

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

lightdm_state_file='/var/lib/lightdm/.cache/lightdm-gtk-greeter/state'
lightdm_state_backup_file="${lightdm_state_file}.sysmaint-boot"
sddm_state_file='/var/lib/sddm/state.conf'
sddm_state_backup_file="${sddm_state_file}.sysmaint-boot"
greetd_conf_dir='/etc/greetd/config.toml.d'
greetd_master_conf_file='/etc/greetd/config.toml'
wlgreet_conf_dir='/etc/greetd/wlgreet.toml.d'
wlgreet_master_conf_file='/etc/greetd/wlgreet.toml'
sysmaint_lightdm_conf_file='/etc/lightdm/lightdm.conf.d/zzz-sysmaint-boot.conf'
sysmaint_sddm_conf_file='/etc/sddm.conf.d/zzz-sysmaint-boot.conf'
sysmaint_greetd_conf_file='/etc/greetd/config.toml.d/50_sysmaint-boot.conf'
sysmaint_wlgreet_conf_file='/etc/greetd/wlgreet.toml.d/50_sysmaint-boot.conf'
old_sysmaint_conf_file_list=(
  '/etc/lightdm/lightdm.conf.d/60_sysmaint-boot.conf'
  '/etc/sddm.conf.d/z-sysmaint-boot.conf'
)
exit_code=0

echo "INFO: Removing sysmaint autologin files because system is shutting down." >&2
safe-rm -f --verbose -- "${sysmaint_lightdm_conf_file}"
safe-rm -f --verbose -- "${sysmaint_sddm_conf_file}"
safe-rm -f -- "${old_sysmaint_conf_file_list[@]}"
safe-rm -f -- "${sysmaint_greetd_conf_file}"
safe-rm -f -- "${sysmaint_wlgreet_conf_file}"

echo "INFO: Restoring display manager state file backups if necessary because system is shutting down." >&2
if [ -f "${lightdm_state_backup_file}" ]; then
   safe-rm -rf --verbose -- "${lightdm_state_file}"
   ## Dummy "loop" to allow skipping code if a command errors out.
   # shellcheck disable=SC2043
   for _ in 1; do
      ## Do not error out and exit in case this fails. Set non-zero exit code but continue execution.
      mv --verbose -- "${lightdm_state_backup_file}" "${lightdm_state_file}" || {
        exit_code=2
        break
      }
      if [ ! -f "${lightdm_state_file}" ] || ! [ -s "${lightdm_state_file}" ]; then
         safe-rm -rf -- "${lightdm_state_file}"
      fi
   done
fi
if [ -f "${sddm_state_backup_file}" ]; then
   safe-rm -rf --verbose -- "${sddm_state_file}"
   # shellcheck disable=SC2043
   for _ in 1; do
      mv --verbose -- "${sddm_state_backup_file}" "${sddm_state_file}" || {
         exit_code=3
         break
      }
      if [ ! -f "${sddm_state_file}" ] || ! [ -s "${sddm_state_file}" ]; then
         safe-rm -rf -- "${sddm_state_file}"
      fi
   done
fi

echo "INFO: Rebuilding greetd config if necessary because system is shutting down." >&2
if [ -d "${greetd_conf_dir}" ]; then
   build-config-file "${greetd_conf_dir}" "${greetd_master_conf_file}"
fi
if [ -d "${wlgreet_conf_dir}" ]; then
   build-config-file "${wlgreet_conf_dir}" "${wlgreet_master_conf_file}"
fi

exit "$exit_code"
