#!/bin/bash

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

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/light_sleep.bsh
source /usr/libexec/helper-scripts/light_sleep.bsh

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/has.sh
source /usr/libexec/helper-scripts/has.sh

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/try_wait_for_audio_ready.bsh
source /usr/libexec/helper-scripts/try_wait_for_audio_ready.bsh

if [ "$(id -un)" = 'sysmaint' ]; then
  printf '%s\n' "ERROR: Cannot log into full desktop session with account 'sysmaint'."
  light_sleep 5
  exit 1
fi

kernel_cmdline=''
if [ -f /proc/cmdline ]; then
  kernel_cmdline="$(cat -- /proc/cmdline)"
elif [ -f /proc/1/cmdline ]; then
  kernel_cmdline="$(cat -- /proc/1/cmdline)"
fi

if [[ "${kernel_cmdline}" =~ 'boot-role=sysmaint' ]]; then
  printf '%s\n' "ERROR: Cannot log into full desktop session when booted in sysmaint session."
  light_sleep 5
  exit 1
fi

## This file should never exist at startup. pcmanfm-qt may create it if force-
## terminated during a reboot though, and if it exists at startup, it will
## break theming badly (desktop turns black, icons end up shifted up, default
## terminal becomes xterm).
if test -f "$HOME/.config/pcmanfm-qt/lxqt/settings.conf.lock"; then
  safe-rm --force -- "$HOME/.config/pcmanfm-qt/lxqt/settings.conf.lock"
fi

## If the user is already in a situation where pcmanfm-qt is broken, we need
## to erase pcmanfm-qt's config before LXQt starts. Unfortunately there's no
## perfect way to tell if the configuration is broken or if the user just
## intentionally set an odd combination of settings, but there is a good
## heuristic we can use. We consider the pcmanfm-qt configuration broken if:
##
## * The wallpaper background color is solid black,
## * No wallpaper image is set,
## * The wallpaper mode is "none",
## * The work area margins are all set to 12,
## * The terminal default is "xterm", and
## * The LXQt panel is at the top.
##
## This is a good heuristic because when the work area margins are all set to
## 12 and the panel is at the top of the screen, the panel will partially
## overlap some icons, which looks broken and is thus a configuration the user
## will probably *not* set. If this occurs in combination with the other
## symptoms of broken configuration, we can semi-safely say that the
## configuration is unintentional and the result of breakage, and wipe it.
# shellcheck disable=SC2043
for _ in 1; do
  test -f "$HOME/.config/pcmanfm-qt/lxqt/settings.conf" &&
    pcmanfm_qt_settings_conf_contents="$(cat -- "$HOME/.config/pcmanfm-qt/lxqt/settings.conf")" || break

  test -f "$HOME/.config/lxqt/panel.conf" &&
    lxqt_panel_conf_contents="$(cat -- "$HOME/.config/lxqt/panel.conf")" || break

  pcmanfm_qt_check_config_lines=(
    'BgColor=#000000'
    'Wallpaper='
    'WallpaperMode=none'
    'WorkAreaMargins=12, 12, 12, 12'
    'Terminal=xterm'
  )
  lxqt_panel_check_config_lines=(
    'position=Top'
  )
  bail_on_config_reset='false'

  for check_config_line in "${pcmanfm_qt_check_config_lines[@]}"; do
    if ! grep --quiet --ignore-case --fixed-strings -- "^${check_config_line}\$" <<< "${pcmanfm_qt_settings_conf_contents}" ; then
      bail_on_config_reset='true'
      break
    fi
  done
  if [ "${bail_on_config_reset}" = 'true' ]; then
    break
  fi

  for check_config_line in "${lxqt_panel_check_config_lines[@]}"; do
    if ! grep --quiet --ignore-case --fixed-strings -- "^${check_config_line}\$" <<< "${lxqt_panel_conf_contents}" ; then
      bail_on_config_reset='true'
      break
    fi
  done
  if [ "${bail_on_config_reset}" = 'true' ]; then
    break
  fi

  safe-rm --recursive --force -- "$HOME/.config/pcmanfm-qt/lxqt"
done

## An empty `~/.config/pcmanfm-qt/lxqt` directory will also cause a black
## screen. Remove the directory if it is empty.
##
## Note that `~/.config/pcmanfm-qt` may contain multiple configuration
## profiles. `lxqt` is only one profile. Therefore we likely do not need to
## remove an empty `~/.config/pcmanfm-qt` directory.
if [ -d "$HOME/.config/pcmanfm-qt/lxqt" ]; then
  rmdir --ignore-fail-on-non-empty -- "$HOME/.config/pcmanfm-qt/lxqt"
fi

do_once_dir="$HOME/.local/share/kicksecure/do_once"
mkdir --parents -- "${do_once_dir}"

if has pactl; then
  ## When not running under a VM, try to set the speaker volume to a safe
  ## default (50%). Only do this once. If the attempt fails for whatever
  ## reason, or the use of a VM is detected, skip setting the speaker volume
  ## and don't try to set it again in the future.
  ## Also in
  ## user-sysmaint-split/usr/libexec/user-sysmaint-split/sysmaint-session-wayland.
  if ! [ -f "${do_once_dir}/set_safe_speaker_volume" ]; then
    touch -- "${do_once_dir}/set_safe_speaker_volume"
    if [ "$(systemd-detect-virt 2>/dev/null || true)" = 'none' ]; then
      try_wait_for_audio_ready
      timeout --kill-after="1" "1" pactl set-sink-volume @DEFAULT_SINK@ 50% || true
    fi
  fi
fi

leaprun signal-wayland-session-started
## For debugging, uncomment this line and comment out the next one.
#exec systemd-cat --identifier=lxqt startlxqtwayland
exec startlxqtwayland >/dev/null 2>&1
