#!/bin/bash

# Wait for DRM subsystem to settle (includes EDID detection)
udevadm settle --timeout=10

# Function to check for physical displays with debug output
check_physical_displays() {
    echo "Starting display check..."
    for card in /sys/class/drm/card*; do
        echo "Checking card: $card"
        for connector in "$card"-*; do
            echo "  Checking connector: $connector"
            if [ -f "$connector/status" ]; then
                status=$(cat "$connector/status")
                echo "    Status file exists, content: $status"
                if grep -q "^connected$" "$connector/status"; then
                    echo "    Found connected status"
                    if echo "$connector" | grep -qE "HDMI|DP|VGA|Virtual"; then
                        echo "    HDMI/DP/VGA/VIRTUAL connector detected and connected"
                        return 0  # success
                    else
                        echo "    Not HDMI/DP/VGA connector"
                    fi
                else
                    echo "    Not connected"
                fi
            else
                echo "    No status file found"
            fi
        done
    done
    echo "No physical display found"
    return 1  # failure
}

# Main logic with debug output
echo "Script starting..."
if check_physical_displays; then
    echo "Physical display connected, no action needed"
else
    echo "No physical display connected, setting up dummy display"
    modprobe dummy
    cp /usr/share/X11/xorg.conf.d/20-display-setup.conf.dummy \
       /usr/share/X11/xorg.conf.d/20-display-setup.conf
fi
