#!/bin/bash
# The desktop add-on's XFCE session, started by devgrail-desktop once Xvnc is
# starting. DISPLAY comes from the app.
set -euo pipefail
: "${DISPLAY:?the app sets DISPLAY}"
x_socket="/tmp/.X11-unix/X${DISPLAY#:}"
for _ in $(seq 1 60); do
    [ -S "$x_socket" ] && break
    sleep 1
done
[ -S "$x_socket" ] || { echo "Xvnc display $DISPLAY did not start" >&2; exit 1; }

# The X server blanks the screen after ten idle minutes by default. Nobody is
# saving a monitor here, and a black desktop reads as a broken one.
xset s off s noblank
xset -dpms 2>/dev/null || true

# The date and time formats the settings helper chose, if it chose any and the
# locale is still generated: a recreated container has only en_US. LC_ALL
# would override them, so it goes, and LANG keeps numbers, sorting and messages
# in en_US. Not grep -q: under pipefail, locale -a can die of SIGPIPE when grep
# quits early.
formats_file="$HOME/.config/devgrail/desktop-locale"
if [ -s "$formats_file" ]; then
    formats="$(head -n 1 "$formats_file")"
    if [[ $formats =~ ^[a-z]{2,3}_[A-Z]{2}$ ]] && locale -a | grep -x "$formats.utf8" >/dev/null; then
        unset LC_ALL
        export LANG=en_US.UTF-8 LC_TIME="$formats.UTF-8" LC_PAPER="$formats.UTF-8" \
            LC_MEASUREMENT="$formats.UTF-8"
    fi
fi

# The scale and settings helpers change settings over this session's private
# D-Bus, so they need the bus address. A stale one from an earlier session is
# removed first; the helpers wait for the new one.
bus_file="$HOME/.cache/devgrail/desktop-bus"
mkdir -p "$(dirname "$bus_file")"
rm -f "$bus_file"
# shellcheck disable=SC2016 # the inner shell expands them, inside the session
exec dbus-run-session -- /bin/sh -c \
    'printf "%s\n" "$DBUS_SESSION_BUS_ADDRESS" > "$1" && exec startxfce4' \
    devgrail-desktop-session "$bus_file"
