#!/bin/sh
# Developer: Hamdy Abou El Anein
# Contact: info@daylightlinux.ch
# SPDX-License-Identifier: GPL-3.0-only
set -eu
export XDG_CURRENT_DESKTOP=Daylight:Fluxbox
export DAYLIGHT_SESSION=1
export GTK_THEME="${GTK_THEME:-Adwaita:dark}"
config=$(/usr/bin/daylight setup-session)
# Fluxbox would overwrite the supplied -rc file on first use if this is absent.
# Existing classic Fluxbox configuration files are never replaced.
(umask 077; mkdir -p "$HOME/.fluxbox")
appearance_pid=
welcome_pid=
wm_pid=
cleanup() {
    if [ -n "$welcome_pid" ]; then kill "$welcome_pid" 2>/dev/null || :; fi
    if [ -n "$appearance_pid" ]; then
        kill "$appearance_pid" 2>/dev/null || :
        wait "$appearance_pid" 2>/dev/null || :
    fi
    if [ -n "$wm_pid" ]; then kill "$wm_pid" 2>/dev/null || :; fi
}
trap cleanup EXIT HUP INT TERM
/usr/bin/fluxbox -rc "$config/fluxbox/init" &
wm_pid=$!
# Keep the X server alive before feh's short-lived connection sets the pixmap.
# A bounded readiness check avoids an unconditional startup sleep.
tries=0
until /usr/bin/xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | grep -q 'window id'; do
    kill -0 "$wm_pid" 2>/dev/null || exit 1
    tries=$((tries + 1))
    if [ "$tries" -ge 50 ]; then echo 'Daylight: Fluxbox did not become ready.' >&2; exit 1; fi
    sleep 0.1
done
wallpaper=$(/usr/bin/daylight settings get wallpaper)
/usr/bin/feh --no-fehbg --bg-max "/usr/share/backgrounds/daylight/$wallpaper"
# This session owns its appearance helper and Conky child. Changes to the
# Daylight user's preferences are applied without touching other desktops.
/usr/bin/python3 /usr/share/daylight/ui/daylight_gui.py --session-appearance &
appearance_pid=$!
/usr/bin/python3 /usr/share/daylight/ui/daylight_gui.py welcome --first-run &
welcome_pid=$!
wait "$wm_pid"
