#!/bin/sh

LOG="${HOME}/.xsession-errors"
exec >>"$LOG" 2>&1

echo "=== $(date -u '+%Y-%m-%dT%H:%M:%SZ') clawdie-xfce-session-inner start ==="

PANEL_TEMPLATE_ROOT="/usr/local/share/clawdie-iso/panel-skel"
PANEL_TEMPLATE_CONFIG="${PANEL_TEMPLATE_ROOT}/.config"
PANEL_STAMP="${HOME}/.config/clawdie/xfce-panel-seeded-v3"

ensure_seeded_panel_profile() {
    mkdir -p "${HOME}/.config/clawdie"

    _panel_xml="${HOME}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml"
    _panel_launcher_dir2="${HOME}/.config/xfce4/panel/launcher-2"
    _panel_launcher_dir3="${HOME}/.config/xfce4/panel/launcher-3"
    _panel_launcher_dir4="${HOME}/.config/xfce4/panel/launcher-4"
    _local_template="${PANEL_TEMPLATE_ROOT}/.local/share/applications/mimeapps.list"
    _local_dest="${HOME}/.local/share/applications/mimeapps.list"

    if [ -f "$PANEL_STAMP" ] && \
       [ -f "$_panel_xml" ] && \
       grep -q 'whiskermenu' "$_panel_xml" 2>/dev/null && \
       grep -q 'clawdie-start' "$_panel_xml" 2>/dev/null && \
       [ -d "$_panel_launcher_dir2" ] && \
       [ -d "$_panel_launcher_dir3" ] && \
       [ -d "$_panel_launcher_dir4" ]; then
        return 0
    fi

    if [ ! -d "$PANEL_TEMPLATE_CONFIG" ]; then
        echo "Panel template missing at ${PANEL_TEMPLATE_CONFIG}; keeping XFCE defaults"
        return 0
    fi

    echo "Restoring seeded XFCE panel profile"
    mkdir -p "${HOME}/.config"
    mkdir -p \
        "${HOME}/.config/xfce4/xfconf/xfce-perchannel-xml" \
        "${HOME}/.config/xfce4/panel"
    cp -R "${PANEL_TEMPLATE_CONFIG}/xfce4/xfconf/." "${HOME}/.config/xfce4/xfconf/"
    cp -R "${PANEL_TEMPLATE_CONFIG}/xfce4/panel/." "${HOME}/.config/xfce4/panel/"
    if [ -f "${PANEL_TEMPLATE_CONFIG}/mimeapps.list" ]; then
        cp "${PANEL_TEMPLATE_CONFIG}/mimeapps.list" "${HOME}/.config/mimeapps.list"
    fi
    if [ -f "$_local_template" ] && [ ! -f "$_local_dest" ]; then
        mkdir -p "${HOME}/.local/share/applications"
        cp "$_local_template" "$_local_dest"
    fi
    : > "$PANEL_STAMP"
}

clear_stale_xfce_sessions() {
    _sessions_dir="${HOME}/.cache/sessions"
    if [ -d "$_sessions_dir" ]; then
        echo "Clearing stale XFCE saved sessions from ${_sessions_dir}"
        rm -f "${_sessions_dir}"/* 2>/dev/null || true
    fi
}

autostart() {
    _name="$1"
    shift
    if command -v "$_name" >/dev/null 2>&1; then
        echo "Starting: $_name $*"
        "$_name" "$@" &
        return 0
    fi
    echo "Missing: $_name"
    return 1
}

manual_xfce_desktop() {
    echo "Starting manual XFCE fallback desktop"

    # Start a minimal XFCE desktop explicitly instead of relying only on a
    # restored saved session. This keeps the live USB useful even when
    # xfce4-session exits early or an optional component is missing.
    autostart xfconfd
    autostart xfsettingsd
    autostart xfwm4 --replace
    autostart xfce4-panel

    # Prefer the native XFCE desktop manager now that xfce4-desktop is part
    # of the live image again. Keep pcmanfm as a last-resort fallback.
    if command -v xfdesktop >/dev/null 2>&1; then
        autostart xfdesktop
    else
        autostart pcmanfm --desktop
    fi

    (
        sleep 8
        if ! pgrep -U "$(id -u)" -x xfce4-panel >/dev/null 2>&1 || \
           ! pgrep -U "$(id -u)" -x xfwm4 >/dev/null 2>&1; then
            echo "Panel or window manager missing after fallback startup; opening rescue terminal"
            if command -v xfce4-terminal >/dev/null 2>&1; then
                xfce4-terminal --title "Clawdie desktop rescue" \
                    --command "sh -lc 'echo XFCE startup fallback. See ~/.xsession-errors.; exec sh'" &
            fi
        fi
    ) &

    # Keep the X session alive while the operator desktop processes run.
    while :; do
        if ! pgrep -U "$(id -u)" -x xfwm4 >/dev/null 2>&1; then
            echo "xfwm4 gone; restarting"
            xfwm4 --replace &
        fi
        if ! pgrep -U "$(id -u)" -x xfce4-panel >/dev/null 2>&1; then
            echo "xfce4-panel gone; ending session"
            exit 1
        fi
        sleep 5
    done
}

ensure_seeded_panel_profile
clear_stale_xfce_sessions

if command -v xfce4-session >/dev/null 2>&1; then
    _xfce4_started_epoch="$(date +%s 2>/dev/null || echo 0)"
    echo "Trying primary desktop path: xfce4-session"
    xfce4-session
    _xfce4_rc=$?
    _xfce4_ended_epoch="$(date +%s 2>/dev/null || echo 0)"
    _xfce4_elapsed=0
    if [ "${_xfce4_started_epoch}" -gt 0 ] && [ "${_xfce4_ended_epoch}" -ge "${_xfce4_started_epoch}" ]; then
        _xfce4_elapsed=$((_xfce4_ended_epoch - _xfce4_started_epoch))
    fi
    echo "xfce4-session exited rc=${_xfce4_rc} after ${_xfce4_elapsed}s"

    # If the session manager stayed up for a while, treat that as a normal
    # desktop exit/logout rather than restarting a fallback desktop behind the
    # operator's back.
    if [ "${_xfce4_rc}" -eq 0 ] || [ "${_xfce4_elapsed}" -ge 15 ]; then
        exit "${_xfce4_rc}"
    fi

    echo "xfce4-session ended too quickly; falling back to manual desktop"
else
    echo "xfce4-session missing; using manual desktop fallback"
fi

manual_xfce_desktop
