#!/usr/bin/env bash
# Pick the largest sane mode on whichever output is connected, at session start.
#
# With no monitor attached the connector's EDID comes from drm.edid_firmware (see the kernel command
# line). That EDID advertises plenty of modes but its *preferred* one is the captured screen's native
# resolution, which may be tiny — GNOME picks preferred, so an 800x480 panel yields an 800x480
# desktop. monitors.xml is the documented override but its monitor matching proved unreliable here,
# so set the mode directly. No-ops when the mode is already right, so it is safe to run repeatedly.
set -eu

MAX_WIDTH="${OFFICER_MAX_WIDTH:-1920}"

# The session's X server may not be up yet when autostart fires.
for _ in $(seq 1 20); do
  xrandr --query >/dev/null 2>&1 && break
  sleep 0.5
done
xrandr --query >/dev/null 2>&1 || exit 0

output=$(xrandr --query | awk '/ connected/ { print $1; exit }')
[ -n "$output" ] || exit 0

# Modes are listed under the output but are not reliably sorted, so pick the widest that fits.
mode=$(
  xrandr --query \
    | sed -n "/^${output} connected/,/^[^ ]/p" \
    | awk '/^[[:space:]]+[0-9]+x[0-9]+/ { print $1 }' \
    | awk -F x -v max="$MAX_WIDTH" '
        { w = $1 + 0; h = $2 + 0 }
        w <= max && (w > bw || (w == bw && h > bh)) { bw = w; bh = h; best = $0 }
        END { if (best) print best }'
)
[ -n "$mode" ] || exit 0

current=$(xrandr --query | awk -v o="$output" '$1 == o { print $3 }' | cut -d+ -f1)
[ "$current" = "$mode" ] && exit 0

xrandr --output "$output" --mode "$mode" || true
