#!/bin/sh
# Rescue-only tty launcher for the Clawdie live XFCE session.
#
# Prefer SDDM for normal boot. This helper intentionally bypasses startx's
# xauth/serverauth setup because installer-derived live environments can make
# startx fail before the client session runs. It starts a local-only Xorg server
# with access control disabled for console rescue/debugging.

set -eu

CLIENT="${1:-/usr/local/bin/clawdie-xfce-session}"
SERVER="${XORG_SERVER:-/usr/local/bin/Xorg}"

if [ ! -x "$CLIENT" ]; then
    echo "ERROR: client session is not executable: $CLIENT" >&2
    exit 1
fi
if [ ! -x "$SERVER" ]; then
    echo "ERROR: Xorg server is not executable: $SERVER" >&2
    exit 1
fi
if ! command -v xinit >/dev/null 2>&1; then
    echo "ERROR: xinit is not available" >&2
    exit 1
fi

_display=""
_i=0
while [ "$_i" -lt 10 ]; do
    if [ ! -e "/tmp/.X${_i}-lock" ] && [ ! -S "/tmp/.X11-unix/X${_i}" ]; then
        _display=":${_i}"
        break
    fi
    _i=$((_i + 1))
done

if [ -z "$_display" ]; then
    echo "ERROR: no free local X display found in :0..:9" >&2
    exit 1
fi

echo "Starting Clawdie rescue X session on ${_display}"
exec xinit "$CLIENT" -- "$SERVER" "$_display" -nolisten tcp -ac
