#!/bin/sh
# SPDX-License-Identifier: MIT
# Copyright (C) 2026 pake <pake@fedora.tw> - https://pomelo-os.org
# init=/usr/bin/desk-session : the Pomelo desktop as the normal session (no display manager, no greeter).
#   compositor -> panel (taskbar) + desktop icons + notification service (each under a small supervisor that restarts it when
#   it crashes) -> autostart entries (~/.config/autostart, /etc/xdg/autostart) -> wait.
#   If the compositor itself dies the whole session is restarted (up to 5 times in 60 s).
#   Log out (desk-power logout) restarts the session; shutdown / restart (desk-power poweroff|reboot) stop everything, sync,
#   ask PID 1 (pomelo-init: /usr/sbin/reboot, /usr/sbin/poweroff) to stop the machine - the kernel powers off or restarts once init has exited.
# Kernel command line knobs (read here): deskrun=SECONDS (leave the session after that long; tests), persist=/dev/vdb (writable
# disk for settings, see docs/SHELL.md), desklang=<code, e.g. en, zh_TW, ja, ko, de> (override LANG).
# Login (docs/LOGIN.md): login=on|off|auto  (auto = on, but off when deskrun= is given, i.e. the VM test harness keeps its root session;
#   off = the old automatic root session), autologin=<user> (log that account in without a password, created when missing; implies login=on),
#   rescue=1 (root shell on the console instead of the desktop: reset a forgotten password).  With login on, the compositor runs as root
#   in /run/pomelo-dm and pomelo-login (greeter, accounts, session as the user) takes the place of the panel/desktop start below.
. /usr/bin/desk-env
export XDG_CONFIG_DIRS=/etc/xdg
export XDG_DATA_DIRS=/usr/share
export POMELO_SPAWN_DIRECT=1
export PATH=/usr/bin:/bin:/sbin:/usr/sbin
RUN=$XDG_RUNTIME_DIR
REQ=$RUN/desk-session.request
SESSION_LOG=/tmp/desk-session.log
PLOG=/persist/log          # boot log on the data partition (when it is mounted writable)
# (boot speed, docs/BOOT-BUDGET.md: no command substitution / pipe in the boot path - every fork+exec is tens of ms on a slow emulated machine)
log() {
    echo "desk-session: $*" >> $SESSION_LOG
    echo "desk-session: $*"
    if [ -d $PLOG ]; then read -r _up _ < /proc/uptime; echo "[$_up] $*" >> $PLOG/desk-session.log; fi
}
# uptime in whole seconds -> NOW (replaces $(date +%s))
now_s() { read -r _up _ < /proc/uptime; NOW=${_up%%.*}; }
# rmf FILE...: rm -f without a fork when there is nothing to remove
rmf() { for _f in "$@"; do if [ -e "$_f" ] || [ -L "$_f" ]; then rm -f "$_f"; fi; done; }
# conf_get FILE KEY -> CONF_V (last KEY=value line; replaces pomelo-accounts get)
conf_get() { CONF_V=; [ -r "$1" ] || return 0; while IFS= read -r _l || [ -n "$_l" ]; do case "$_l" in "$2="*) CONF_V=${_l#*=};; esac; done < "$1"; }
# boot stage time stamps (/proc/pomelo_boot_times) and the boot splash control file (docs/BOOT.md)
mark() { { echo "mark $1" > /proc/pomelo_splash; } 2>/dev/null; }
# the kernel console stays off the screen while the boot splash is up: make it show the text now (failure diagnostics)
splash_off() { { echo log > /proc/pomelo_splash; } 2>/dev/null; }
mark session-start
LEVEL_MIN=0; NOACCEL=; SAFEBOOT=
DESK_RUN=
read -r CMDLINE < /proc/cmdline
for w in $CMDLINE; do
    case "$w" in
    deskrun=*) DESK_RUN=${w#deskrun=};;
    persist=*) PERSIST=${w#persist=};;
    deskcursor=*) export POMELO_CURSOR_TRACE=1;;
    deskdebug=*) DEBUG=1;;
    pomelo.nogpu=1) LEVEL_MIN=1; SAFEBOOT=1;;
    pomelo.noaccel=1) NOACCEL=1; SAFEBOOT=1;;
    desksocketwait=*) DESK_SOCKET_WAIT=${w#desksocketwait=};;
    deskfail=*) DESKFAIL=${w#deskfail=};;     # test aid: deskfail=die | hang  makes every compositor start fail
    imedebug=*) export POMELO_INPUT_DEBUG=1;;
    login=*) LOGINP=${w#login=};;
    autologin=*) AUTOLOGIN=${w#autologin=};;
    rescue=1) RESCUE=1;;
    logintheme=*) LOGINTHEME=${w#logintheme=};;     # light | dark: the look of the login screen / setup wizard (machine.conf "theme")
    loginfail=greeter) LOGIN_GREETER="--greeter /bin/false";;     # test aid: the greeter always dies (text-login fallback chain)
    desklang=*) LANGOVERRIDE=1; export LANG=${w#desklang=}.UTF-8; [ "${w#desklang=}" = en ] && export LANG=en_US.UTF-8;;
    esac
done
rmf "$REQ"
# deskdebug=1: show the component logs on the console (test aid)
if [ -n "${DEBUG:-}" ]; then : > /tmp/compositor.log; tail -n0 -F /tmp/pomelo-input.log /tmp/compositor.log /tmp/pomelo-panel.log /tmp/pomelo-desktop.log /tmp/pomelo-notify.log /tmp/loginprobe.log /tmp/pomelo-login.log /tmp/pomelo-login.log.greeter 2>/dev/null & fi

if [ -x /usr/bin/desk-prep ]; then
    # native front end (docs/BOOT-BUDGET.md): C:\ (desk-mounts), the persist= disk and the settings links, no child processes
    /usr/bin/desk-prep mounts
    eval "$(/usr/bin/desk-prep persist "${PERSIST:-}")"
else
[ -x /usr/bin/desk-mounts ] && /usr/bin/desk-mounts   # writable persistent C:\ (docs/PERSISTC.md)
# ---- settings: ~/.config lives on the ramfs root unless a writable disk is given (persist=/dev/vdb) ----
mkdir -p /persist 2>/dev/null
# persist=/dev/vdb | persist=LABEL=pomelo-data | persist=PARTUUID=<uuid>: LABEL / PARTUUID are looked up in /proc/fsprobe (blkid style)
case "${PERSIST:-}" in
LABEL=*|PARTUUID=*|UUID=*)
    key=${PERSIST%%=*}; val=${PERSIST#*=}; val=${val#\"}; val=${val%\"}
    for t in $(seq 1 50); do   # the disk may still be probing (50 x 0.2 s)
        dev=$(sed -n "s|^\(/dev/[^:]*\):.* $key=\"$val\".*|\1|p" /proc/fsprobe 2>/dev/null | head -n1)
        [ -n "$dev" ] && break; sleep 0.2     # (was 1 s)
    done
    if [ -n "$dev" ]; then log "persist $PERSIST is $dev"; PERSIST=$dev; else log "persist $PERSIST: no such partition"; PERSIST=; fi;;
esac
if [ -n "${PERSIST:-}" ] && [ -b "$PERSIST" ]; then
    if mount "$PERSIST" /persist 2>/dev/null || mount -t ext4 "$PERSIST" /persist 2>/dev/null || mount -t ext2 "$PERSIST" /persist 2>/dev/null; then
        mkdir -p /persist/config
        rm -rf /root/.config; ln -s /persist/config /root/.config
        export XDG_CONFIG_HOME=/root/.config
        # browser profile (cookies, history, local storage: ~/.local/share/pomelo-browser) and downloads live on the data partition too
        mkdir -p /persist/share /persist/Downloads /root/.local
        rm -rf /root/.local/share /root/Downloads; ln -s /persist/share /root/.local/share; ln -s /persist/Downloads /root/Downloads
        export XDG_DATA_HOME=/root/.local/share
        mkdir -p $PLOG
        [ -f $PLOG/desk-session.log ] && mv -f $PLOG/desk-session.log $PLOG/desk-session.prev.log
        [ -f $PLOG/kernel.log ] && mv -f $PLOG/kernel.log $PLOG/kernel.prev.log
        cp $SESSION_LOG $PLOG/desk-session.log 2>/dev/null
        log "settings persist on $PERSIST (boot log in $PLOG)"
    else
        log "cannot mount $PERSIST: settings are lost at power off"
    fi
else
    log "no persist= disk: settings in /root/.config are lost at power off (image root is read-only)"
fi
fi
mark settings-ready
# ---- accounts and login screen (docs/LOGIN.md) ----
LOGIN=${LOGINP:-auto}
[ -n "${AUTOLOGIN:-}" ] && [ "$LOGIN" = auto ] && LOGIN=on
[ "$LOGIN" = auto ] && { if [ -n "$DESK_RUN" ]; then LOGIN=off; else LOGIN=on; fi; }
[ -x /usr/bin/pomelo-login ] && [ -x /usr/bin/pomelo-greeter ] || LOGIN=off
CRUN=$RUN; COMP_ARGS=
if [ "$LOGIN" = on ]; then
    if [ -x /usr/bin/desk-prep ]; then /usr/bin/desk-prep accounts "${AUTOLOGIN:-}" >> $SESSION_LOG 2>&1 || log "desk-accounts failed"
    else /usr/bin/desk-accounts "${AUTOLOGIN:-}" >> $SESSION_LOG 2>&1 || log "desk-accounts failed"; fi
    [ -n "${LOGINTHEME:-}" ] && POMELO_ACCOUNTS=/etc/pomelo/accounts /usr/bin/pomelo-accounts set theme "$LOGINTHEME"
    CRUN=/run/pomelo-dm; COMP_ARGS="--ipc-socket $CRUN/compositor.sock"
    export POMELO_LOGIN=1; unset POMELO_SPAWN_DIRECT     # the compositor (root) starts programs for key bindings as the logged-in user only
    read -r _pers < /run/pomelo-dm/persistent 2>/dev/null
    log "login: on (autologin ${AUTOLOGIN:-none}, accounts persistent=${_pers:-}), compositor runtime dir $CRUN"
else
    log "login: off (root session)"
fi
[ -n "${RESCUE:-}" ] && { /usr/bin/desk-rescue "rescue=1 on the kernel command line"; }
[ -d /root/.config/autostart ] && [ -d /root/.config/pomelo ] || mkdir -p /root/.config/pomelo /root/.config/autostart
# computer name chosen in System Settings > About (docs/MENUS.md): lives on the data partition, applied at every session start
if [ -s /root/.config/pomelo/hostname ]; then read -r _hn < /root/.config/pomelo/hostname; hostname "$_hn" 2>/dev/null && log "computer name $_hn"; fi
# Assistant (docs/ASSISTANT.md): pin it in the Start menu once, only when it is installed and the user has not chosen a pinned list yet
_haspin=
if [ -x /usr/bin/pomelo-assistant ]; then
    [ -r /root/.config/pomelo/settings.conf ] && while IFS= read -r _l || [ -n "$_l" ]; do case "$_l" in startmenu.pinned*) _haspin=1; break;; esac; done < /root/.config/pomelo/settings.conf
fi
if [ -x /usr/bin/pomelo-assistant ] && [ -z "$_haspin" ]; then
    echo 'startmenu.pinned=pomelo-files,pomelo-terminal,pomelo-edit,pomelo-calc,pomelo-calendar,pomelo-system,pomelo-paint,pomelo-viewer,pomelo-writer,pomelo-sheet,pomelo-monitor,pomelo-software,pomelo-assistant' >> /root/.config/pomelo/settings.conf
fi
# ---- helpers ----
# settings chosen in System Settings that only take effect at session start: language (system.language) and keyboard layout;
# read again on every (re)start of the session, so log out + in applies them
# setting KEY -> SETTING_V (last "KEY [spaces] = [spaces] value" line of settings.conf; no sed/tail: builtins only)
setting() {
    SETTING_V=
    [ -r /root/.config/pomelo/settings.conf ] || return 0
    while IFS= read -r _l || [ -n "$_l" ]; do
        case "$_l" in
        "$1"*=*)
            _k=${_l%%=*}; while [ "${_k% }" != "$_k" ]; do _k=${_k% }; done
            if [ "$_k" = "$1" ]; then SETTING_V=${_l#*=}; while [ "${SETTING_V# }" != "$SETTING_V" ]; do SETTING_V=${SETTING_V# }; done; fi;;
        esac
    done < /root/.config/pomelo/settings.conf
}
read_session_settings() {
    if [ -z "${LANGOVERRIDE:-}" ]; then
        setting system.language; sl=$SETTING_V
        # every catalog libpomelo ships (libpomelo/i18n/*.tsv); the pane System Settings > Language & Region writes 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
    fi
    # CJK language other than Traditional Chinese: the right Noto Sans (SC/JP/KR) answers for "Noto Sans CJK TC", see etc/fonts/lang
    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
    setting keyboard.layout; kl=$SETTING_V
    [ "$LOGIN" = on ] && { conf_get /etc/pomelo/accounts/machine.conf keyboard; kl=$CONF_V; }     # login on: the layout is a machine setting (login screen, setup wizard)
    if [ -n "$kl" ]; then export POMELO_XKB_LAYOUT=$kl XKB_DEFAULT_LAYOUT=$kl; fi
    setting layout; ly=$SETTING_V; case "$ly" in windows|taskbar) ;; *) ly=pomelo;; esac     # desktop layout (docs/LAYOUT.md): panel, launcher, Files, compositor read it themselves, live
    log "desktop layout $ly"
    _all=; [ -r /root/.config/pomelo/settings.conf ] && while IFS= read -r _l || [ -n "$_l" ]; do case "$_l" in "#"*) ;; *) _all="$_all$_l;";; esac; done < /root/.config/pomelo/settings.conf
    log "language ${LANG}, keyboard layout ${POMELO_XKB_LAYOUT:-us} (settings: $_all)"
}

# supervise NAME COMPOSITOR_PID CMD...: run CMD, restart it when it exits while the compositor lives (max 5 restarts / 30 s)
supervise() {
    name=$1; cp=$2; shift 2
    (   fails=0; now_s; t0=$NOW
        while kill -0 "$cp" 2>/dev/null; do
            "$@" 2>/tmp/$name.log
            rc=$?
            kill -0 "$cp" 2>/dev/null || break
            now_s; now=$NOW
            [ $((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 ) &
    echo $! >> $RUN/supervisors
}
# autostart: Exec= of every *.desktop in the two directories (user entries override /etc/xdg ones of the same name)
autostart() {
    for d in /root/.config/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" >/tmp/autostart-${b%.desktop}.log 2>&1 &
        done
    done
}

stop_clients() {
    [ -n "${LPID:-}" ] && { kill $LPID 2>/dev/null; for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 $LPID 2>/dev/null || break; sleep 0.3; done; kill -9 $LPID 2>/dev/null; LPID=; }
    rm -f $RUN/pomelo-input.state $RUN/pomelo-input.sock
    for p in $(cat $RUN/supervisors 2>/dev/null); do kill $p 2>/dev/null; done
    rm -f $RUN/supervisors
    # (the loop variable must not be `n`: that is the failure counter of the session rounds below, and this function runs at the end of every
    #  round that got as far as a compositor socket - the counter was reset to 0 each time, so such a crash loop never reached give_up)
    for nm in pomelo-input pomelo-panel pomelo-desktop pomelo-notify pomelo-launcher pomelo-files pe_load pomelo-calc pomelo-terminal pomelo-edit; do
        for pid in $(pidof $nm 2>/dev/null); do kill $pid 2>/dev/null; done
    done
    sleep 0.3     # (was 1 s)
}


# login service (docs/LOGIN.md): pomelo-login shows the greeter, checks passwords and starts desk-user-session as the user
LPID=; LCRASH=0; LOGIN_UP=
login_start() {
    rm -f /tmp/desk-user-session.up
    : >> /tmp/pomelo-login.log
    /usr/bin/pomelo-login --run $CRUN --state /var/lib/pomelo-dm --request $REQ --compositor-pid $cpid --log /tmp/pomelo-login.log \
        ${AUTOLOGIN:+--autologin $AUTOLOGIN} ${LOGIN_GREETER:-} 2>>/tmp/pomelo-login.log &
    LPID=$!; AUTOLOGIN=      # autologin once per boot: after log out the greeter comes back
    mark login-start
    log "login service started (pid $LPID)"
}
login_watch() {
    if [ -z "$LOGIN_UP" ] && [ -f /tmp/desk-user-session.up ]; then LOGIN_UP=1; log "session up (user session, compositor $cpid, level $LEVEL)"; fi
    if [ -n "$LPID" ] && ! kill -0 $LPID 2>/dev/null; then
        wait $LPID 2>/dev/null; lrc=$?; LPID=
        if [ -s "$REQ" ]; then log "login service ended: $(cat $REQ)"; kill $cpid 2>/dev/null
        elif [ $LCRASH -lt 2 ] && kill -0 $cpid 2>/dev/null; then LCRASH=$((LCRASH+1)); log "login service died ($(describe_rc $lrc)), restart $LCRASH"; login_start
        else log "login service keeps failing ($(describe_rc $lrc))"; echo "login service failed" > /tmp/login-failed; kill $cpid 2>/dev/null; fi
    fi
}

# ---------------------------------------------------------------------------------------------------------------------------
# Session rounds.  A round = one compositor lifetime.  Every way a round can end is logged with the exit status; a failed round
# (compositor died or never created its socket) prints the compositor's log on screen and saves it to the data partition, and the
# next round starts in a safer mode:
#   level 0  normal (card0 only)
#   level 1  the spare generic card (firmware frame buffer, "simpledrm"), software rendering, no hardware cursor
#   level 2  as 1, no input-device probing at start, only the panel (no desktop icons / notifications / input method / autostart)
#   level 3  give up: diagnostics on screen, a shell on the console (and, once, a reboot into "safe graphics")
# pomelo.nogpu=1 on the kernel command line starts at level 1 (spare generic card, full desktop).
# ---------------------------------------------------------------------------------------------------------------------------
SOCKET_WAIT=${DESK_SOCKET_WAIT:-120}       # seconds the compositor may take to create its socket (slow virtual machines)
ROUND=0
ncards() { NCARDS=0; for _c in /dev/dri/card*; do [ -e "$_c" ] && NCARDS=$((NCARDS + 1)); done; }
dri_names() { DRI_NAMES=; for _c in /dev/dri/*; do [ -e "$_c" ] && DRI_NAMES="$DRI_NAMES${_c##*/} "; done; }
# generic_card -> GENERIC_CARD (the card "simpledrm" in the kernel log)
generic_card() {
    GENERIC_CARD=
    [ -r /proc/kmsg ] || return 0
    while IFS= read -r _l; do case "$_l" in "drm: /dev/dri/card"*" is simpledrm"*) _l=${_l#drm: /dev/dri/}; GENERIC_CARD=${_l%% *}; break;; esac; done < /proc/kmsg
}
apply_level() {
    unset WLR_DRM_DEVICES
    export WLR_RENDERER=pixman WLR_NO_HARDWARE_CURSORS=1 WLR_DRM_NO_ATOMIC=1
    # with several cards (native driver + spare generic one) never let wlroots drive both
    ncards
    if [ "$LEVEL" -ge 1 ] && [ "$NCARDS" -gt 1 ]; then
        generic_card; [ -n "$GENERIC_CARD" ] && export WLR_DRM_DEVICES=/dev/dri/$GENERIC_CARD
    elif [ "$NCARDS" -gt 1 ]; then
        export WLR_DRM_DEVICES=/dev/dri/card0
    fi
    [ "$LEVEL" -ge 2 ] && export WLR_LIBINPUT_NO_DEVICES=1
    [ -n "${NOACCEL:-}" ] && export LIBGL_ALWAYS_SOFTWARE=1 GSK_RENDERER=cairo
    dri_names
    log "round $ROUND: level $LEVEL, cards: ${DRI_NAMES}WLR_DRM_DEVICES=${WLR_DRM_DEVICES:-<all>}"
}
save_logs() {
    [ -d $PLOG ] || return 0
    cp /tmp/compositor.log $PLOG/compositor-round$ROUND.log 2>/dev/null
    cp /proc/kmsg $PLOG/kernel.log 2>/dev/null
    cp $SESSION_LOG $PLOG/desk-session.log 2>/dev/null
    cp /tmp/pomelo-login.log $PLOG/pomelo-login.log 2>/dev/null; cp /tmp/pomelo-login.log.greeter $PLOG/greeter.log 2>/dev/null
    sync
}
round_failed() {     # $1 = why
    log "round $ROUND FAILED: $1"
    splash_off
    echo "---- compositor.log (last 30 lines) ----"; tail -n 30 /tmp/compositor.log 2>/dev/null
    save_logs
}
describe_rc() { if [ "$1" -gt 128 ] 2>/dev/null; then echo "killed by signal $(($1 - 128))"; else echo "exit status $1"; fi; }

session_once() {
    ROUND=$((ROUND + 1)); now_s; ROUND_T0=$NOW
    read_session_settings
    apply_level
    unset WAYLAND_DISPLAY     # a leftover value from the previous round would make wlroots start the nested Wayland backend
    rmf "$RUN"/wayland-0 "$RUN"/wayland-0.lock "$CRUN"/wayland-0 "$CRUN"/wayland-0.lock
    [ "$LOGIN" = on ] && echo $LEVEL > $CRUN/level
    mark compositor-start
    case "${DESKFAIL:-}" in
    die)  { echo "deskfail=die: simulated compositor failure (wlr_backend_start failed)" >&2; exit 1; } >/tmp/compositor.log 2>&1 & ;;
    hang) { echo "deskfail=hang: simulated hang" >&2; sleep 1000; } >/tmp/compositor.log 2>&1 & ;;
    *)    XDG_RUNTIME_DIR=$CRUN /usr/bin/pomelo-compositor $COMP_ARGS >/tmp/compositor.log 2>&1 & ;;
    esac
    cpid=$!
    echo $cpid > $RUN/compositor.pid
    if [ -x /usr/bin/desk-prep ]; then
        # one native process polls every 20 ms (the shell loop below forked a `sleep 0.05` 20 times a second: on a slow emulated CPU that
        # competed with the compositor it was waiting for)
        /usr/bin/desk-prep waitsock "$CRUN/wayland-0" $cpid $SOCKET_WAIT
    else
    i=0; limit=$((SOCKET_WAIT * 20))
    while [ $i -lt $limit ] && [ ! -S "$CRUN/wayland-0" ] && kill -0 $cpid 2>/dev/null; do
        sleep 0.05; i=$((i+1))
        [ $((i % 200)) -eq 0 ] && { read -r _up _ < /proc/uptime; log "waiting for the compositor socket ($((i / 20)) s of $SOCKET_WAIT, uptime $_up)"; }
    done
    fi
    if [ ! -S "$CRUN/wayland-0" ]; then
        if kill -0 $cpid 2>/dev/null; then
            ROUND_WHY="compositor still running but no socket after ${SOCKET_WAIT} s (hung)"
            kill -TERM $cpid 2>/dev/null; sleep 2; kill -KILL $cpid 2>/dev/null
        else
            wait $cpid 2>/dev/null; rc=$?
            ROUND_WHY="compositor died before creating its socket ($(describe_rc $rc))"
        fi
        wait $cpid 2>/dev/null
        round_failed "$ROUND_WHY"
        return 1
    fi
    export WAYLAND_DISPLAY=wayland-0
    mark compositor-socket
    if [ "$LOGIN" = on ]; then
        login_start
    else
    mark panel-start
    supervise pomelo-panel $cpid /usr/bin/pomelo-panel
    if [ "$LEVEL" -lt 2 ]; then
        sleep 0.3     # (was 1 s) the panel gets the CPU first; the desktop icons follow
        supervise pomelo-desktop $cpid /usr/bin/pomelo-desktop
        # notifications, input method and autostart entries are not needed for the first frame: they start a little later
        # (on a slow CPU they would compete with the panel for it)
        (
        sleep 1.5
        supervise pomelo-notify $cpid /usr/bin/pomelo-notify
        # input method (docs/IME.md): Zhuyin etc. for native Wayland programs through the compositor's input-method-v2
        # (not when input.framework = none in settings.conf)
        setting input.framework
        [ "$SETTING_V" = none ] || supervise pomelo-input $cpid /usr/bin/pomelo-input
        autostart
        ) &
        echo $! >> $RUN/supervisors
    fi
    mark session-up
    log "session up (compositor $cpid, level $LEVEL)"
    fi
    t=0
    while kill -0 $cpid 2>/dev/null; do
        sleep 1; t=$((t+1))
        [ "$LOGIN" = on ] && login_watch
        [ -n "$DESK_RUN" ] && [ $t -ge "$DESK_RUN" ] && { echo test-end > $REQ; kill $cpid 2>/dev/null; }
    done
    wait $cpid 2>/dev/null; rc=$?
    now_s; ROUND_WHY="compositor ended after $(( NOW - ROUND_T0 )) s ($(describe_rc $rc))"
    [ -f /tmp/login-failed ] && { ROUND_WHY="login service failed (greeter), $ROUND_WHY"; rm -f /tmp/login-failed; }
    log "$ROUND_WHY"
    stop_clients
    return 0
}

# Desktop impossible: say why on screen, keep the console alive with a shell, once (when it can be written) leave a flag on the
# ESP that makes the loader boot "safe graphics" next time.
give_up() {
    splash_off
    log "GIVING UP after $ROUND rounds: $ROUND_WHY"
    save_logs
    echo; echo "############ THE DESKTOP COULD NOT START ############"
    echo "Last problem: $ROUND_WHY"
    echo "Photograph this screen, or send the serial log / the files in the data partition folder log/ (see README)."
    /usr/bin/desk-diag 30
    if [ -z "${SAFEBOOT:-}" ]; then
        esp=$(sed -n 's|^\(/dev/[^:]*\):.* TYPE="vfat".*|\1|p' /proc/fsprobe 2>/dev/null | head -n1)
        if [ -n "$esp" ] && mkdir -p /esp && mount -t vfat "$esp" /esp 2>/dev/null; then
            if [ ! -e /esp/EFI/pomelo/safe.flag ] && echo safe > /esp/EFI/pomelo/safe.flag 2>/dev/null; then
                sync; umount /esp 2>/dev/null
                log "wrote \\EFI\\pomelo\\safe.flag: the next boot uses safe graphics (delete the file to undo)"
                echo "Restarting in SAFE GRAPHICS mode in 20 seconds (the loader menu also offers it; delete \\EFI\\pomelo\\safe.flag to undo)."
                sleep 20; save_logs; /usr/sbin/reboot
            fi
            umount /esp 2>/dev/null
        fi
    fi
    echo "Type  desk-diag  to see this again,  reboot  to restart,  desk-session-retry  to try the desktop again."
    while :; do if [ "$LOGIN" = on ]; then /usr/bin/desk-rescue "the desktop could not start"; else /bin/sh </dev/console >/dev/console 2>&1; fi; sleep 1; done
}

LEVEL=$LEVEL_MIN; n=0; now_s; t0=$NOW; ROUND_WHY=
while :; do
    session_once; ok=$?
    action=; [ -f "$REQ" ] && read -r action < "$REQ"; rmf "$REQ"
    case "$action" in
    poweroff|reboot|test-end) break;;
    logout) log "log out: restarting the session"; n=0; LEVEL=$LEVEL_MIN; continue;;
    esac
    now_s; now=$NOW
    # a round that lasted a minute or more was a working session that crashed: start over at the normal level
    # (login mode: a round in which the login service failed for good is a failure however long its three attempts took)
    if [ $ok -eq 0 ] && [ $((now - ROUND_T0)) -ge 60 ] && [ "${ROUND_WHY#login service failed}" = "$ROUND_WHY" ]; then n=0; LEVEL=$LEVEL_MIN; t0=$now; fi
    n=$((n + 1))
    [ $ok -ne 0 ] && round_failed_done=1
    [ $ok -eq 0 ] && round_failed "$ROUND_WHY"
    if [ $n -ge 4 ]; then give_up; fi
    LEVEL=$((LEVEL + 1)); [ $LEVEL -gt 2 ] && LEVEL=2
    log "restarting the session in safer mode (level $LEVEL, failure $n of 4)"
    sleep 1
done
log "end: ${action:-crash-loop}"
case "$action" in reboot) { echo restart > /proc/pomelo_splash; } 2>/dev/null;; *) { echo shutdown > /proc/pomelo_splash; } 2>/dev/null;; esac   # boot splash: "shutting down" / "restarting"
echo "--- compositor log"; tail -4 /tmp/compositor.log
save_logs
# stop every remaining process (daemons, helpers): the kernel checks for leaks when init exits
# (was: sleep 1 twice) programs that write files on exit (browser profile, Windows apps) get a second, the rest a moment
if pidof pomelo-browser pe_load >/dev/null 2>&1; then w=1; else w=0.3; fi
kill -TERM -1 2>/dev/null; sleep $w; kill -KILL -1 2>/dev/null; sleep 0.2
sync
case "$action" in
reboot) /usr/sbin/reboot;;
poweroff) /usr/sbin/poweroff;;
esac
exit 0
