#!/bin/bash

# This may be called before qubes-session is fully initialized, so do not rely
# on having DISPLAY set from there
export DISPLAY=:0

# Wait for Xorg complete startup
while ! xrandr -q &>/dev/null; do sleep 0.1; done

output_no=0
output_base=DUMMY
output_max=$[ `xrandr | grep -c ^$output_base` - 1 ]

xrandr_cmd=""

while read w h x y w_mm h_mm extra; do
    output_name=$output_base$output_no
    mode_name="QB${w}x${h}"
    if ! xrandr | grep -q $mode_name; then
        cvt=`cvt $w $h | tail -n 1 | cut -d ' ' -f 3-`
        xrandr --newmode $mode_name $cvt
    fi
    xrandr --addmode $output_name $mode_name
    # Do not set it at once b/c xserver resets position after output gets
    # "connected" - the case for first mode set
    xrandr_cmd="$xrandr_cmd --output $output_name --mode $mode_name --pos ${x}x${y}"
    # Set physical dimensions if provided (for HiDPI being handled automatically)
    if [ -n "$w_mm" -a -n "$h_mm" ]; then
        xrandr_cmd="$xrandr_cmd --set WIDTH_MM $w_mm --set HEIGHT_MM $h_mm"
    fi
    output_no=$[ $output_no + 1]
done

for i in `seq $output_no $output_max`; do
    xrandr_cmd="$xrandr_cmd --output $output_base$i --off"
done

xrandr $xrandr_cmd
xrandr --query >/dev/null
