#!/bin/bash

# --- Configuration ---
# Set your desired resolution and refresh rate here.
DESIRED_MODE="1920x1080"
DESIRED_RATE="60"
# ---------------------

echo "Starting dynamic X11 resolution script..."

# 1. Detect the primary connected output
# xrandr output: finds connected monitors, extracts the one marked 'primary' or the first one connected.
# Example: HDMI-1 connected primary 1920x1080+0+0 (...)
PRIMARY_OUTPUT=$(xrandr --query | grep ' connected' | awk '/primary/ {print $1; exit} {print $1; exit}')

if [ -z "$PRIMARY_OUTPUT" ]; then
    echo "ERROR: No connected display output found."
    exit 1
fi

echo "Detected primary output: $PRIMARY_OUTPUT"

# 2. Check if the desired mode is supported for this output
MODE_SUPPORTED=$(xrandr --query | grep "$PRIMARY_OUTPUT" -A 100 | grep -w "$DESIRED_MODE" | awk '{print $1}' | head -n 1)

if [ -z "$MODE_SUPPORTED" ]; then
    echo "WARNING: Desired mode $DESIRED_MODE is not directly supported or listed."
    echo "Attempting to create and add the mode..."
    
    # Check if 'cvt' is available (for custom modeline generation)
    if ! command -v cvt &> /dev/null; then
        echo "ERROR: 'cvt' command not found. Cannot create custom mode. Please install 'xorg-server-utils'."
        echo "You can manually try to set a different supported mode."
        exit 1
    fi
    
    # Generate modeline and extract the necessary part
    MODELINE_RAW=$(cvt $(echo "$DESIRED_MODE" | tr 'x' ' ') $DESIRED_RATE | grep 'Modeline' | cut -d' ' -f2-)
    
    if [ -z "$MODELINE_RAW" ]; then
        echo "ERROR: Could not generate modeline for $DESIRED_MODE@$DESIRED_RATE Hz."
        exit 1
    fi
    
    MODE_NAME=$(echo "$MODELINE_RAW" | awk '{print $1}' | tr -d '"')
    
    # Add the new mode
    xrandr --newmode "$MODE_NAME" $MODELINE_RAW
    if [ $? -ne 0 ]; then
        echo "ERROR: Failed to add new mode."
        exit 1
    fi
    
    # Attach the new mode to the output
    xrandr --addmode "$PRIMARY_OUTPUT" "$MODE_NAME"
    if [ $? -ne 0 ]; then
        echo "ERROR: Failed to attach new mode to $PRIMARY_OUTPUT. Attempting to clean up."
        xrandr --delmode "$PRIMARY_OUTPUT" "$MODE_NAME" 2>/dev/null
        xrandr --rmmode "$MODE_NAME" 2>/dev/null
        exit 1
    fi
    
    # The mode name to use for setting is the one generated by cvt
    MODE_TO_SET="$MODE_NAME"
    
else
    # Mode is supported, check for the specific refresh rate
    RATE_CHECK=$(xrandr --query | grep -A 100 "$PRIMARY_OUTPUT" | grep -w "$DESIRED_MODE" | grep -w "$DESIRED_RATE\.\*\|\*$DESIRED_RATE\.\*")
    
    if [ -z "$RATE_CHECK" ]; then
        # Use the standard listed mode name
        MODE_TO_SET="$DESIRED_MODE"
        RATE_OPTION="--rate $DESIRED_RATE"
        echo "Mode $DESIRED_MODE is supported. Setting with explicit rate $DESIRED_RATE Hz."
    else
        # Found the resolution with the specific rate (marked with *)
        MODE_TO_SET="$DESIRED_MODE"
        RATE_OPTION="" # No need for --rate if the *+ mode is already at the desired rate
        echo "Mode $DESIRED_MODE is already listed with or near the current rate."
    fi
fi

# 3. Set the resolution
echo "Applying settings: xrandr --output $PRIMARY_OUTPUT --mode $MODE_TO_SET $RATE_OPTION"

# Execute the final command
xrandr --output "$PRIMARY_OUTPUT" --mode "$MODE_TO_SET" $RATE_OPTION

if [ $? -eq 0 ]; then
    echo "SUCCESS: Display resolution set to $MODE_TO_SET ${DESIRED_RATE}Hz on $PRIMARY_OUTPUT."
else
    echo "FAILURE: xrandr command failed. Check output for errors."
fi
