#!/bin/sh
set -e

echo "[amadeos-dm] Initializing amadeOS Display Manager on vt7..."

# Only clients holding this cookie may connect to the X server. The greeter runs as
# root, so an open X server would let any local process read the password entry.
XAUTH_DIR=/run/amadeos
XAUTH_FILE="$XAUTH_DIR/Xauthority"
install -d -m 0700 -o root -g root "$XAUTH_DIR"
export DISPLAY=:0
export XAUTHORITY="$XAUTH_FILE"

x_server_running() {
    # With a cookie, ask the server itself; a leftover socket file alone proves nothing.
    if [ -s "$XAUTH_FILE" ] && command -v xset >/dev/null 2>&1; then
        xset -q >/dev/null 2>&1
    else
        [ -e "/tmp/.X11-unix/X0" ] && [ -s "$XAUTH_FILE" ]
    fi
}

# Start Xorg server on vt7 if not already active
if ! x_server_running; then
    echo "[amadeos-dm] Creating X authorization cookie..."
    rm -f "$XAUTH_FILE"
    (umask 077 && : > "$XAUTH_FILE")
    xauth -q -f "$XAUTH_FILE" add :0 . "$(mcookie)"

    echo "[amadeos-dm] Starting Xorg display server on vt7..."
    Xorg :0 vt7 -auth "$XAUTH_FILE" -nolisten tcp -background none >/var/log/amadeos-xorg.log 2>&1 &
    XORG_PID=$!

    # Wait for Xorg to be ready and accept connections
    READY=0
    for i in $(seq 1 60); do
        if [ -e "/tmp/.X11-unix/X0" ]; then
            if command -v xset >/dev/null 2>&1; then
                if xset -q -display :0 >/dev/null 2>&1; then
                    echo "[amadeos-dm] Xorg is ready and responding on :0 (iteration $i)"
                    READY=1
                    break
                fi
            else
                READY=1
                break
            fi
        fi
        sleep 0.1
    done

    if [ "$READY" -eq 0 ]; then
        echo "[amadeos-dm] Warning: Xorg socket wait timed out, proceeding..."
    fi

    # Switch console to VT7 so user sees the graphical display
    if command -v chvt >/dev/null 2>&1; then
        chvt 7 2>/dev/null || true
    fi
fi

# The user session gets the cookie from SessionLauncher; access is never opened up with xhost.

if [ -f /etc/default/locale ]; then
    . /etc/default/locale
fi
export LANG="${LANG:-de_DE.UTF-8}"
export LC_ALL="${LC_ALL:-de_DE.UTF-8}"

# Keyboard layout of the greeter from /etc/default/keyboard (console-setup); the session applies the
# user's own settings later.
XKBLAYOUT=""
XKBVARIANT=""
XKBOPTIONS=""
if [ -f /etc/default/keyboard ]; then
    . /etc/default/keyboard
fi
if command -v setxkbmap >/dev/null 2>&1 && [ -n "$XKBLAYOUT" ]; then
    echo "[amadeos-dm] Applying keyboard layout ($XKBLAYOUT)..."
    # shellcheck disable=SC2086
    setxkbmap -layout "$XKBLAYOUT" ${XKBVARIANT:+-variant "$XKBVARIANT"} ${XKBOPTIONS:+-option "$XKBOPTIONS"} 2>/dev/null || true
fi

echo "[amadeos-dm] Launching Java Display Manager daemon..."
exec /usr/libexec/amadeos-dm :0


