#!/bin/bash
# scale PERCENT: scales the running XFCE session's UI.
#
# The viewer asks for a desktop at its real pixel count on a high-density
# screen, then calls this through PUT /api/scale so windows and text are not
# half size.
# 200 doubles everything (GTK's window scaling factor, and the window manager's
# double-size theme). The steps between only raise the font DPI, which also
# sets the browser's page zoom: GTK cannot scale windows by a fraction. The
# pointer keeps its size: the viewer's browser draws the desktop's cursor
# image at one CSS pixel per desktop pixel, unscaled, so it is already right.
#
# Exit codes are read by devgrail-desktop (localapi.go): 2 for a scale it does
# not offer, 3 when the session is not up within about 15 seconds.
set -euo pipefail

percent="${1:-}"
case "$percent" in
    100) factor=1 dpi=96 theme=Default ;;
    125) factor=1 dpi=120 theme=Default ;;
    150) factor=1 dpi=144 theme=Default-hdpi ;;
    175) factor=1 dpi=168 theme=Default-hdpi ;;
    200) factor=2 dpi=96 theme=Default-xhdpi ;;
    *) echo "unsupported scale: $percent" >&2; exit 2 ;;
esac

bus_file="$HOME/.cache/devgrail/desktop-bus"
: "${DISPLAY:?the app sets DISPLAY}"
# Read again on every try: a desktop that is just starting may still have the
# previous session's file, or none yet.
for _ in $(seq 1 30); do
    if [ -s "$bus_file" ]; then
        DBUS_SESSION_BUS_ADDRESS="$(cat "$bus_file")"
        export DBUS_SESSION_BUS_ADDRESS
        if xfconf-query -c xsettings -p /Gdk/WindowScalingFactor -n -t int -s "$factor" 2>/dev/null; then
            xfconf-query -c xsettings -p /Xft/DPI -n -t int -s "$dpi"
            xfconf-query -c xfwm4 -p /general/theme -n -t string -s "$theme"
            exit 0
        fi
    fi
    sleep 0.5
done
echo 'the desktop session is not running' >&2
exit 3
