#!/usr/bin/env bash
set -e

# Wait for a Wayland session to appear (up to 30s)
for i in $(seq 1 15); do
  WAYLAND_USER=$(loginctl list-sessions --no-legend 2>/dev/null \
    | awk '{print $3}' \
    | while read -r u; do
        if ls /run/user/$(id -u "$u")/wayland-* >/dev/null 2>&1; then
          echo "$u"
          break
        fi
      done)
  [ -n "$WAYLAND_USER" ] && break
  sleep 2
done

if [ -z "$WAYLAND_USER" ]; then
  echo "No active Wayland session found, exiting."
  exit 0
fi

UID_VAL=$(id -u "$WAYLAND_USER")
WL_DISPLAY=$(ls /run/user/$UID_VAL/wayland-* 2>/dev/null | head -1 | xargs basename)

run_as_user() {
  sudo -u "$WAYLAND_USER" \
    XDG_RUNTIME_DIR=/run/user/$UID_VAL \
    WAYLAND_DISPLAY=$WL_DISPLAY \
    "$@"
}

run_as_user wlr-randr | grep -E "^[A-Z]" | awk '{print $1}' | while read -r output; do
  SUPPORTED=$(run_as_user wlr-randr --output "$output" 2>/dev/null)
  for mode in "1920x1080" "1680x1050" "1600x900" "1440x900" "1280x1024" "1280x720"; do
    if echo "$SUPPORTED" | grep -q "$mode"; then
      echo "Setting $output to $mode"
      run_as_user wlr-randr --output "$output" --mode "$mode" || true
      break
    fi
  done
done
