#!/bin/sh
# display-setup.sh — LightDM greeter display + HiDPI setup
#
# Runs as root on the greeter's X server BEFORE the greeter starts (wired up via
# `display-setup-script=` in /etc/lightdm/lightdm.conf).
#
# Why this exists: lightdm-gtk-greeter is an Xorg client. On a multi-monitor box
# a bare X server may leave some outputs disabled (a "blank" monitor at the login
# screen) and drops the login form onto whichever output it picks as primary —
# often a small side panel. It also defaults to 96 DPI, so on a 4K panel the
# whole greeter is tiny.
#
# So, name-agnostically (survives GPU/cable/port changes):
#   1. Enable every connected output at its preferred mode, laid out left→right.
#   2. Make the widest active output primary, so the login form lands on the main
#      (here: 4K) monitor instead of a small one.
#   3. Raise the DPI so text, icons, form and cursor are legibly large. GTK reads
#      Xft.dpi from the X resource database; `xrandr --dpi` covers anything that
#      reads the server core DPI instead.
#
# Tuning: bump/lower the 144 DPI (96 = 1.0x, 144 = 1.5x, 192 = 2.0x) to taste.

LOG=/var/log/lightdm/display-setup.log
exec >>"$LOG" 2>&1
echo "=== display-setup $(date) ==="

[ -x /usr/bin/xrandr ] || { echo "xrandr missing — skipping"; exit 0; }

# 1. Enable + position every connected output, left to right in connection order.
prev=""
for out in $(xrandr --query | awk '/ connected/{print $1}'); do
    if [ -z "$prev" ]; then
        xrandr --output "$out" --auto --pos 0x0
    else
        xrandr --output "$out" --auto --right-of "$prev"
    fi
    prev="$out"
done

# 2. Primary = widest currently-active output (parse the WxH+X+Y geometry).
best_out=$(xrandr --query | awk '
    / connected/{o=$1}
    match($0, /[0-9]+x[0-9]+\+[0-9]+\+[0-9]+/){
        split(substr($0, RSTART, RLENGTH), a, /[x+]/)
        if (a[1]+0 > best){ best=a[1]+0; bo=o }
    }
    END{ print bo }')
[ -n "$best_out" ] && xrandr --output "$best_out" --primary

# 3. HiDPI scaling for the greeter.
xrandr --dpi 144
if [ -n "$DISPLAY" ] && command -v xrdb >/dev/null 2>&1; then
    printf 'Xft.dpi: 144\nXcursor.size: 36\n' | xrdb -merge
fi

echo "primary=${best_out:-<none>} dpi=144"
