#!/bin/bash
# This script is for non systemd installations of wkgtk-html2pdf
# It is used to contitionally start xvfb there are no existing 
# desktops available for webkit to use to generate pdf's

LOG_FILE="/var/log/wkgtk-html2pdf.log"

log_message() {
    # Generate a clean timestamp string
    TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
    MSG="[$TIMESTAMP] (XVFB-INIT) $1"

    # Route A: Write directly to your explicit text log if it exists
    if [ -w "$LOG_FILE" ]; then
        echo "$MSG" >> "$LOG_FILE"
    else
        # Route B: Universal POSIX fallback to ensure high visibility
        logger -t wk2gtkpdf "$MSG"
    fi
}


# Desktop Conflict Check: Probe for active local X11 or Wayland display sockets
if [ -d /tmp/.X11-unix ] && [ "$(ls -A /tmp/.X11-unix 2>/dev/null)" ] || [ -e "$XDG_RUNTIME_DIR/wayland-0" ] || ls /run/user/*/wayland-* &>/dev/null; then
    log_message "Active graphical display environment detected (DISPLAY=$DISPLAY, WAYLAND=$WAYLAND_DISPLAY)."
    log_message "Aborting headless Xvfb daemon startup to prevent display socket conflict."
    exit 0
fi


log_message "No active graphics layer found. Initializing high-availability framework on display :99..."

# Headless Environment Options
export DISPLAY=:99
export WEBKIT_FORCE_SANDBOX=0
export WEBKIT_DISABLE_COMPOSITING_MODE=1

# Force Mesa/Skia to render entirely via CPU rasterisation
export LIBGL_ALWAYS_SOFTWARE=1

# Tell GTK4 to use the modern Skia rendering path but force the software backend
export GSK_RENDERER=ngskia 
# Fallback flag just in case the specific micro-version uses the older nomenclature
export GSK_RENDER_NODE=software

# Force pure X11 surface translation and fully kill portals/dbus dialogs
export GDK_BACKEND=x11
export GTK_USE_PORTAL=0
export GDK_DEBUG=no-portals
export GDK_USE_XDG_PORTAL=0

# Direct Command Execution
exec /usr/bin/Xvfb :99 -screen 0 1024x768x24 -nolisten tcp -noreset

