#!/bin/bash
# raveos-monitor-setup - Auto-detect monitors and generate Hyprland config
# Sets each monitor to max resolution at 60Hz
#
# Usage: raveos-monitor-setup.sh [--hypr-dir PATH]
#   Default hypr dir: ~/.config/hypr

HYPR_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/hypr"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --hypr-dir) HYPR_DIR="$2"; shift 2 ;;
        *) shift ;;
    esac
done

MONITORS_CONF="$HYPR_DIR/monitors.conf"
WORKSPACES_CONF="$HYPR_DIR/workspaces.conf"

# Find connected monitors via DRM sysfs
declare -a MON_NAMES
declare -a MON_RESOLUTIONS
declare -a MON_WIDTHS

for card_output in /sys/class/drm/card*-*; do
    [[ ! -d "$card_output" ]] && continue

    status=$(cat "$card_output/status" 2>/dev/null)
    [[ "$status" != "connected" ]] && continue

    # Get output name: card0-DP-1 → DP-1, card1-HDMI-A-1 → HDMI-A-1
    raw_name=$(basename "$card_output")
    name="${raw_name#card*-}"

    # Get available modes (first line = highest resolution)
    modes_file="$card_output/modes"
    if [[ -f "$modes_file" ]]; then
        max_mode=$(head -1 "$modes_file")
        if [[ -n "$max_mode" ]]; then
            # Extract width from resolution (e.g., 2560x1440 → 2560)
            width="${max_mode%%x*}"
            MON_NAMES+=("$name")
            MON_RESOLUTIONS+=("$max_mode")
            MON_WIDTHS+=("$width")
        fi
    fi
done

# If no monitors found, use fallback
if [[ ${#MON_NAMES[@]} -eq 0 ]]; then
    cat > "$MONITORS_CONF" << 'EOF'
# Auto-generated by raveos-monitor-setup
# No monitors detected - using fallback
monitor=,preferred,auto,1
EOF
    cat > "$WORKSPACES_CONF" << 'EOF'
# Auto-generated by raveos-monitor-setup
# No monitors detected
EOF
    echo "No monitors detected, using fallback config"
    exit 0
fi

# Generate monitors.conf
cat > "$MONITORS_CONF" << 'EOF'
# Auto-generated by raveos-monitor-setup
# Run raveos-monitor-setup.sh to reconfigure monitors
EOF

pos_x=0
for ((i=0; i<${#MON_NAMES[@]}; i++)); do
    echo "monitor=${MON_NAMES[$i]}, ${MON_RESOLUTIONS[$i]}@60, ${pos_x}x0, 1" >> "$MONITORS_CONF"
    pos_x=$((pos_x + MON_WIDTHS[i]))
done

# Generate workspaces.conf - distribute 10 workspaces across monitors
cat > "$WORKSPACES_CONF" << 'EOF'
# Auto-generated by raveos-monitor-setup
EOF

num_monitors=${#MON_NAMES[@]}
ws_per_mon=$((10 / num_monitors))
remaining=$((10 % num_monitors))

ws=1
for ((i=0; i<num_monitors; i++)); do
    count=$ws_per_mon
    [[ $i -lt $remaining ]] && ((count++))

    for ((j=0; j<count; j++)); do
        echo "workspace=$ws, monitor:${MON_NAMES[$i]}, persistent:1" >> "$WORKSPACES_CONF"
        ((ws++))
    done
done

echo "Monitor setup complete: ${#MON_NAMES[@]} monitor(s) configured"
for ((i=0; i<${#MON_NAMES[@]}; i++)); do
    echo "  ${MON_NAMES[$i]}: ${MON_RESOLUTIONS[$i]}@60"
done
