#!/bin/bash

## Copyright (C) 2024 - 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=./sysmaint-session-shared
source /usr/libexec/user-sysmaint-split/sysmaint-session-shared

export XDG_SESSION_TYPE='x11'

window_manager_list=(
   '/usr/bin/xfwm4'
   # Add other window managers here later
)
selected_window_manager=''
for window_manager in "${window_manager_list[@]}"; do
   if [ -e "${window_manager}" ]; then
      selected_window_manager="${window_manager}"
      break
   fi
done

sysmaint_app_list=(
   '/usr/bin/sysmaint-panel'
   '/usr/bin/x-terminal-emulator'
)
selected_sysmaint_app=''
for sysmaint_app in "${sysmaint_app_list[@]}"; do
   if [ -e "${sysmaint_app}" ]; then
      selected_sysmaint_app="${sysmaint_app}"
      break
   fi
done

system_tray_list=(
   '/usr/bin/trayer'
)
system_tray_arg_list=(
   '--edge top --align right --SetPartialStrut true'
)

for (( idx = 0; idx < ${#system_tray_list[@]}; idx++ )); do
   if [ -e "${system_tray_list[idx]}" ]; then
      selected_system_tray="${system_tray_list[idx]}"
      selected_system_tray_args="${system_tray_arg_list[idx]}"
      break
   fi
done

if [ -z "${selected_window_manager}" ]; then
   printf "%s\n" "$0: ERROR: Could not find a supported window manager!" >&2
   exit 1
fi
if [ -z "${selected_sysmaint_app}" ]; then
   printf "%s\n" "$0: ERROR: Could not find a supported sysmaint app!" >&2
   exit 1
fi

dbus-update-activation-environment --systemd --all

write_sysmaint_account_specific_config_once

"${selected_window_manager}" &
# Needed to prevent window ordering problems
light_sleep 1
if [ -n "${selected_system_tray}" ]; then
   # shellcheck disable=SC2086
   "${selected_system_tray}" ${selected_system_tray_args} &
fi
"${selected_sysmaint_app}" &
sysmaint_app_pid="$!"

start_user_background_services

wait "${sysmaint_app_pid}"
