#!/usr/bin/env bash

# Change according to your needs
XORG_CONF_SOURCE="/etc/X11/xorg.conf.d/xorg.conf.bak"
XORG_CONF_DEST="/etc/X11/xorg.conf.d/xorg.conf"

CONN_STATUS=""

# Function to check and switch displays
switch_display() {
    if check_monitor_connected; then
        if [ "$CONN_STATUS" != "yes" ]; then
            # Disable the dummy display
            if [ -e "$XORG_CONF_DEST" ]; then
                sudo mv $XORG_CONF_DEST $XORG_CONF_SOURCE
                sudo systemctl restart lightdm
            fi
            CONN_STATUS="yes"
        fi
    else
        if [ "$CONN_STATUS" != "no" ]; then
            # Enable the dummy display
            if [ -e "$XORG_CONF_SOURCE" ]; then
                sudo mv $XORG_CONF_SOURCE $XORG_CONF_DEST
                sudo systemctl restart lightdm
            fi
            CONN_STATUS="no"
        fi
    fi
}

# Function to check if a monitor is connected
check_monitor_connected() {
    for card in /sys/class/drm/card*; do
        if [ -e "$card/status" ]; then
            status=$(cat "$card/status")
            if [ "$status" = "connected" ]; then
                return 0  # Monitor connected
            fi
        fi
    done
    return 1  # No monitor connected
}

# Continuous loop to monitor for changes
while true; do
    switch_display
    # Check every second for changes
    sleep 1
done
