#!/bin/sh
# SPDX-License-Identifier: MIT
# Copyright (C) 2026 pake <pake@fedora.tw> - https://pomelo-os.org
# desk-user-session: the desktop session of ONE logged-in user (docs/LOGIN.md).  Started by pomelo-login with the user's identity
# (uid/gid/groups already dropped, HOME, XDG_RUNTIME_DIR=/run/user/<uid>, WAYLAND_DISPLAY set).  Not root: panel, desktop icons,
# notifications, input method, autostart entries.  The compositor is a separate, root, system component (desk-session starts it).
# It ends when pomelo-login sends SIGTERM (log out, shutdown) - then it stops its clients and exits.
DESK_USER_SESSION=1; export DESK_USER_SESSION
. /usr/bin/desk-env
export XDG_CONFIG_HOME=$HOME/.config XDG_CACHE_HOME=$HOME/.cache XDG_DATA_HOME=$HOME/.local/share
export XDG_CONFIG_DIRS=/etc/xdg XDG_DATA_DIRS=/usr/share POMELO_SPAWN_DIRECT=1
export PATH=/usr/bin:/bin:/sbin:/usr/sbin
RUN=$XDG_RUNTIME_DIR
LOG=$HOME/.cache/desk-user-session.log
log() { echo "[$(cut -d' ' -f1 /proc/uptime)] desk-user-session($(id -un)): $*" >> $LOG 2>/dev/null; echo "desk-user-session: $*"; }
mkdir -p $XDG_CONFIG_HOME/pomelo $XDG_CONFIG_HOME/autostart $XDG_CACHE_HOME $XDG_DATA_HOME 2>/dev/null
setting() { sed -n "s/^$1[ ]*=[ ]*//p" $XDG_CONFIG_HOME/pomelo/settings.conf 2>/dev/null | tail -1; }
# language and keyboard layout of THIS user (settings.conf; the first login gets the choice made in the setup wizard)
sl=$(setting system.language)
case "$sl" in
    en|en_US) export LANG=en_US.UTF-8 LANGUAGE=en;;
    zh_TW) export LANG=zh_TW.UTF-8; unset LANGUAGE;;
    zh_CN|ja|ko|de|es|fr|it|ru|th|vi|id|pt_BR)
        case "$sl" in zh_CN) lc=zh_CN;; ja) lc=ja_JP;; ko) lc=ko_KR;; de) lc=de_DE;; es) lc=es_ES;; fr) lc=fr_FR;; it) lc=it_IT;;
            ru) lc=ru_RU;; th) lc=th_TH;; vi) lc=vi_VN;; id) lc=id_ID;; pt_BR) lc=pt_BR;; esac
        export LANG=$lc.UTF-8 LANGUAGE=$sl;;
esac
unset FONTCONFIG_FILE
case "$LANG" in zh_CN*) fl=zh_CN;; ja*) fl=ja;; ko*) fl=ko;; *) fl=;; esac
[ -n "$fl" ] && [ -f /etc/fonts/lang/$fl.conf ] && export FONTCONFIG_FILE=/etc/fonts/lang/$fl.conf
kl=$(setting keyboard.layout)
[ -n "$kl" ] && export POMELO_XKB_LAYOUT=$kl XKB_DEFAULT_LAYOUT=$kl
LEVEL=$(cat /run/pomelo-dm/level 2>/dev/null); LEVEL=${LEVEL:-0}
log "start (uid $(id -u), home $HOME, display $WAYLAND_DISPLAY, level $LEVEL, lang $LANG)"
SUPS=
supervise() {
    name=$1; shift
    (   fails=0; t0=$(date +%s)
        while [ -S "$RUN/$WAYLAND_DISPLAY" ]; do
            "$@" 2>$XDG_CACHE_HOME/$name.log
            rc=$?
            [ -S "$RUN/$WAYLAND_DISPLAY" ] || break
            now=$(date +%s)
            [ $((now - t0)) -gt 30 ] && { fails=0; t0=$now; }
            fails=$((fails + 1)); log "$name exited ($rc), restart $fails"
            [ $fails -ge 5 ] && { log "$name keeps crashing, giving up"; break; }
            sleep 1
        done ) &
    SUPS="$SUPS $!"
}
autostart() {
    for d in $XDG_CONFIG_HOME/autostart /etc/xdg/autostart; do
        for f in $d/*.desktop; do
            [ -f "$f" ] || continue
            b=$(basename "$f")
            case " $seen " in *" $b "*) continue;; esac
            seen="$seen $b"
            grep -qi '^Hidden=true' "$f" && continue
            grep -qi '^X-Pomelo-Autostart-enabled=false' "$f" && continue
            only=$(sed -n 's/^OnlyShowIn=//p' "$f" | head -1)
            [ -n "$only" ] && case ";$only" in *";Pomelo;"*|*";Pomelo") ;; *) continue;; esac
            cmd=$(sed -n 's/^Exec=//p' "$f" | head -1 | sed 's/ %[a-zA-Z]//g')
            [ -n "$cmd" ] || continue
            log "autostart $b: $cmd"
            sh -c "$cmd" >$XDG_CACHE_HOME/autostart-${b%.desktop}.log 2>&1 &
        done
    done
}
stop_all() {
    trap '' TERM
    for p in $SUPS; do kill $p 2>/dev/null; done
    for n in pomelo-input pomelo-panel pomelo-desktop pomelo-notify pomelo-launcher pomelo-files pe_load pomelo-calc pomelo-terminal pomelo-edit pomelo-system; do
        for pid in $(pidof $n 2>/dev/null); do kill $pid 2>/dev/null; done
    done
    rm -f $RUN/pomelo-input.state $RUN/pomelo-input.sock
    log "stopped"
    exit 0
}
trap stop_all TERM INT HUP
mkdir -p $RUN 2>/dev/null; chmod 700 $RUN 2>/dev/null
# the environment of this session, for programs the compositor starts for key bindings (desk-spawn)
( export -p > $RUN/session.env ) 2>/dev/null; chmod 600 $RUN/session.env 2>/dev/null
# the session's first moment: wait (a little) for the socket the compositor opened for this user
i=0; while [ ! -S "$RUN/$WAYLAND_DISPLAY" ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done
[ -S "$RUN/$WAYLAND_DISPLAY" ] || log "WARNING: no $RUN/$WAYLAND_DISPLAY"
{ echo "mark panel-start" > /proc/pomelo_splash; } 2>/dev/null
supervise pomelo-panel /usr/bin/pomelo-panel
if [ "$LEVEL" -lt 2 ]; then
    sleep 0.3
    supervise pomelo-desktop /usr/bin/pomelo-desktop
    (
    sleep 1.5
    supervise pomelo-notify /usr/bin/pomelo-notify
    [ "$(setting input.framework)" = none ] || supervise pomelo-input /usr/bin/pomelo-input
    autostart
    wait
    ) &
    SUPS="$SUPS $!"
fi
{ echo "mark session-up" > /proc/pomelo_splash; } 2>/dev/null
log "session up"
grep -q "loginprobe=1" /proc/cmdline && /usr/bin/desk-login-probe &
( : > /tmp/desk-user-session.up ) 2>/dev/null     # (a subshell: a failing redirection of a special builtin would end the whole script)
# a supervisor loop that sleeps is interrupted by TERM; `sleep & wait` lets the trap run at once
while :; do sleep 1000 & wait $!; done
