#!/bin/bash

if [ $# -ne 2 ]; then
  xrandr
  echo >&2
  echo "Usage: $0 <width> <height>" >&2
  exit -1
fi

MONITORS=~/.config/monitors.xml

if [ ! -e "$MONITORS" ]; then
  echo "Can't open $MONITORS!" >&2
  echo "Please use gnome-control-center first, setup some resolution and come back here..." >&2
  exit -1
fi


# Setup given resolution into xrandr
eval `cvt -v $1 $2\
	| sed -ne 's,Modeline "\(.*\)_.*"\(.*\),MODE="\1" MODELINE="\2",p'`
xrandr --newmode $MODE $MODELINE
OUTPUT="`xrandr --current|sed -ne 's,^\(.*\) connected.*,\1,p'|head -1`"
xrandr --addmode "$OUTPUT" "$MODE" 
# xrandr --output "$OUTPUT" --mode "$MODE"



# Build ~/.config/monitors.xml
ML=( $MODELINE )
RATE=${ML[0]}
WIDTH=${ML[1]}
HEIGHT=${ML[5]}
mv -v $MONITORS $MONITORS.backup
xmlstarlet ed \
  -u "/monitors/configuration/output[@name='$OUTPUT']/width" -v "$WIDTH" \
  -u "/monitors/configuration/output[@name='$OUTPUT']/height" -v "$HEIGHT" \
  -u "/monitors/configuration/output[@name='$OUTPUT']/rate" -v "$RATE" \
  $MONITORS.backup > $MONITORS


# Ask gnome-settings-daemon to apply changes
dbus-send --session --print-reply --dest=org.gnome.SettingsDaemon /org/gnome/SettingsDaemon/XRANDR org.gnome.SettingsDaemon.XRANDR_2.ApplyConfiguration int64:0 int64:0



# See https://wiki.gnome.org/RandR
