#!/bin/sh
# amadeOS X11 desktop session: starts the window manager under supervision, the autostart scripts
# and the front panel. Started by the display manager (amadeos-dm) or by startx through ~/.xinitrc.
set -u

# Ensure display is configured
if [ $# -gt 0 ] && [ -n "$1" ]; then
    export DISPLAY="$1"
else
    export DISPLAY="${DISPLAY:-:0}"
fi

export HOME="${HOME:-/home/$(id -un 2>/dev/null || echo amadeos)}"
export USER="${USER:-$(id -un 2>/dev/null || echo amadeos)}"

# Default configuration values: the window manager (package amadeos-wm) and the panel (/usr/bin/amadeos-panel,
# the alternative registered by amadeos-panel-cde or another panel package)
WM_COMMAND="${WM_COMMAND:-/usr/bin/amadeos-wm}"
PANEL_COMMAND="${PANEL_COMMAND:-/usr/bin/amadeos-panel}"
WM_ENABLED="${WM_ENABLED:-true}"
WM_AUTO_RESTART="${WM_AUTO_RESTART:-true}"
# Logs in ~/.cache/amadeos/logs next to the applications' logs; the Tools drawer's log viewer lists them.
LOG_DIR="${XDG_CACHE_HOME:-${HOME:-/tmp}/.cache}/amadeos/logs"
WM_LOG_FILE="$LOG_DIR/wm.log"
SESSION_LOG_FILE="$LOG_DIR/session.log"
AUTOSTART_APP="${AUTOSTART_APP:-panel}"

# Language: the greeter passes the language chosen at login. Remember it for the desktop
# (~/.config/amadeos/locale.conf, read by the panel and every amade application) unless the file
# already holds that language, possibly with a region such as de_AT.
LOCALE_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/amadeos/locale.conf"
if [ -n "${AMADEOS_LOGIN_LOCALE:-}" ]; then
    login_language="$(printf '%s' "$AMADEOS_LOGIN_LOCALE" | cut -c1-2)"
    stored_language="$(head -n 1 "$LOCALE_CONF" 2>/dev/null | cut -c1-2)"
    if [ "$login_language" != "$stored_language" ]; then
        mkdir -p "$(dirname "$LOCALE_CONF")" && printf '%s\n' "$AMADEOS_LOGIN_LOCALE" > "$LOCALE_CONF"
    fi
fi
unset AMADEOS_LOGIN_LOCALE

# Load system configuration manifest if present
if [ -f "/etc/amadeos/session.conf" ]; then
    . "/etc/amadeos/session.conf"
fi

# Load user configuration manifest override if present
USER_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/amadeos/session.conf"
if [ -f "$USER_CONF" ]; then
    . "$USER_CONF"
fi

# Ensure log files are writable by current user; fallback to /tmp if necessary
mkdir -p "$(dirname "$SESSION_LOG_FILE")" "$(dirname "$WM_LOG_FILE")" 2>/dev/null || true
if ! touch "$SESSION_LOG_FILE" 2>/dev/null; then
    SESSION_LOG_FILE="/tmp/.amadeos-session-$(id -u 2>/dev/null || echo 1000).log"
fi
if ! touch "$WM_LOG_FILE" 2>/dev/null; then
    WM_LOG_FILE="/tmp/.amadeos-wm-$(id -u 2>/dev/null || echo 1000).log"
fi

# Redirect stdout/stderr to session log file
exec > "$SESSION_LOG_FILE" 2>&1
echo "[amadeos-session] Starting session at $(date)"
echo "[amadeos-session] Session config: WM=$WM_COMMAND, PANEL=$PANEL_COMMAND, DISPLAY=$DISPLAY, WM_ENABLED=$WM_ENABLED, AUTO_RESTART=$WM_AUTO_RESTART"

report_error_and_fallback() {
    msg="$1"
    echo "[amadeos-session] ERROR: $msg" >&2
    if command -v xterm >/dev/null 2>&1; then
        echo "[amadeos-session] Launching fallback xterm..." >&2
        exec xterm -title "amadeOS Session Error" -hold -e sh -c "echo 'amadeOS Session Error:'; echo '$msg'; echo; echo 'Press Ctrl+C or close window to exit session.'; exec sh"
    fi
    exit 1
}

if [ "$WM_ENABLED" = "true" ] && [ ! -x "$WM_COMMAND" ]; then
    report_error_and_fallback "Window manager not found at $WM_COMMAND (package amadeos-wm)."
fi

SESSION_ACTIVE=1
WM_SUPERVISOR_PID=""
WM_CHILD_PID=""

cleanup_session() {
    echo "[amadeos-session] Cleaning up session processes..."
    SESSION_ACTIVE=0
    if [ -f "${HOME:-/tmp}/.amadeos-wm.pid" ]; then
        WM_PID="$(cat "${HOME:-/tmp}/.amadeos-wm.pid" 2>/dev/null || true)"
        if [ -n "$WM_PID" ]; then
            kill "$WM_PID" 2>/dev/null || true
        fi
        rm -f "${HOME:-/tmp}/.amadeos-wm.pid"
    fi
    if [ -n "$WM_CHILD_PID" ]; then
        kill "$WM_CHILD_PID" 2>/dev/null || true
    fi
    if [ -n "$WM_SUPERVISOR_PID" ]; then
        kill "$WM_SUPERVISOR_PID" 2>/dev/null || true
    fi
    echo "[amadeos-session] Session terminated cleanly at $(date)"
}
trap cleanup_session EXIT INT TERM HUP

# Start Window Manager under supervision
if [ "$WM_ENABLED" = "true" ]; then
    echo "[amadeos-session] Launching amadeOS Window Manager supervisor..."
    (
        while [ "$SESSION_ACTIVE" = "1" ]; do
            echo "[amadeos-wm-supervisor] Spawning WM daemon on $DISPLAY..." >> "$WM_LOG_FILE"
            "$WM_COMMAND" "$DISPLAY" >> "$WM_LOG_FILE" 2>&1 &
            CURR_WM_PID=$!
            echo "$CURR_WM_PID" > "${HOME:-/tmp}/.amadeos-wm.pid"
            wait "$CURR_WM_PID"
            EXIT_CODE=$?
            echo "[amadeos-wm-supervisor] WM daemon exited with code $EXIT_CODE" >> "$WM_LOG_FILE"
            
            if [ "$SESSION_ACTIVE" = "1" ] && [ "$WM_AUTO_RESTART" = "true" ]; then
                echo "[amadeos-wm-supervisor] Auto-restarting WM daemon in 1s..." >> "$WM_LOG_FILE"
                sleep 1
            else
                break
            fi
        done
    ) &
    WM_SUPERVISOR_PID=$!
    echo "[amadeos-session] WM supervisor started (PID $WM_SUPERVISOR_PID)"

    # Wait for Window Manager readiness (poll for EWMH property or brief settling delay)
    READY=0
    for i in 1 2 3 4 5 6 7 8 9 10; do
        if command -v xprop >/dev/null 2>&1; then
            if xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | grep -q "window id"; then
                echo "[amadeos-session] Window Manager initialized and claimed EWMH support (iteration $i)"
                READY=1
                break
            fi
        fi
        sleep 0.1
    done
    if [ "$READY" -eq 0 ]; then
        echo "[amadeos-session] Window Manager started (proceeding after settling delay)"
    fi
fi

# Run drop-in autostart scripts, except the ones switched off in Settings > Startup
# (~/.config/amadeos/startup.conf: disabled=40-amadeos-clipboard,...)
STARTUP_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/amadeos/startup.conf"
DISABLED_SCRIPTS=""
if [ -r "$STARTUP_CONF" ]; then
    DISABLED_SCRIPTS=",$(grep -m1 '^disabled=' "$STARTUP_CONF" | cut -d= -f2- | tr -d ' \r'),"
fi
for autostart_dir in "/etc/amadeos/autostart.d" "${XDG_CONFIG_HOME:-$HOME/.config}/amadeos/autostart.d"; do
    if [ -d "$autostart_dir" ]; then
        for script in "$autostart_dir"/*; do
            if [ -x "$script" ] && [ ! -d "$script" ]; then
                case "$DISABLED_SCRIPTS" in
                    *",$(basename "$script"),"*)
                        echo "[amadeos-session] Autostart script switched off in Settings: $script"
                        continue ;;
                esac
                echo "[amadeos-session] Executing autostart script: $script"
                "$script" &
            fi
        done
    fi
done

# The user's programs of ~/.config/autostart (Settings > Startup), once
if ls "${XDG_CONFIG_HOME:-$HOME/.config}"/autostart/*.desktop >/dev/null 2>&1; then
    echo "[amadeos-session] Starting the programs of ~/.config/autostart"
    /usr/libexec/amadeos-session autostart &
fi

# Launch primary application
echo "[amadeos-session] Starting primary application: $AUTOSTART_APP"
if [ "$AUTOSTART_APP" = "panel" ] || [ "$AUTOSTART_APP" = "cde-panel" ] || [ "$AUTOSTART_APP" = "demo" ]; then
    if [ ! -x "$PANEL_COMMAND" ]; then
        report_error_and_fallback "Panel not found at $PANEL_COMMAND (package amadeos-panel-cde or another provider of amadeos-panel)."
    fi
    "$PANEL_COMMAND" "$@"
else
    # Execute configured custom command
    eval "$AUTOSTART_APP" "$@"
fi
APP_EXIT_CODE=$?
echo "[amadeos-session] Primary application exited with code $APP_EXIT_CODE"

exit "$APP_EXIT_CODE"
