#!/bin/bash
# Filename:      grml-resolution
# Purpose:       change X resolution via a simple menu frontend
# Authors:       Florian Keller <florian.keller@zuerich.ch>, (c) Michael Prokop <mika@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2.
################################################################################

PN=$(basename $0)
RESOLUTION=$(mktemp)
ERROR=$(mktemp)

bailout(){
  rm -f $RESOLUTION $ERROR
  exit $1
}

trap bailout 1 2 3 15

main(){
# menu
COUNTER=0
STRING=""

# current mode
CURRENT_NUM=$(xrandr | awk '/\*/ {print $1}' | tr -d '*')
CURRENT_RESOLUTION=$(xrandr | awk '/\*/ {print $2 $3 $4}')

# menu
for i in $(xrandr | awk {'print $2$3$4'} | grep "^[0-9]") ; do
  STRING="$STRING $COUNTER $i"
  ((COUNTER++))
done

# Menue Tool
dialog --title "$PN" --menu "Change X resolution via xrandr (current resolution: $CURRENT_RESOLUTION):" 0 0 0 $STRING 2>$RESOLUTION
retval=$?
case $retval in
      (1)   echo "Cancel pressed." ; exit 1 ;;
      (255) echo "ESC pressed."    ; exit 1 ;;
esac

CHOSE=$(cat $RESOLUTION)

if [ "$CHOSE" = "$CURRENT_NUM" ] ; then
   dialog --title "$PN" --msgbox "Chosen resolution corresponds to current resolution. No changes needed." 0 0
elif [ -n "$CHOSE" ] ; then
  xrandr -s $CHOSE 2>$ERROR && \
  dialog --title "$PN" --msgbox "Running xrandr with resolution was succesful." 0 0 || \
  dialog --title "$PN" --msgbox "Error when running xrandr with resolution $CHOSE: `cat $ERROR`" 0 0
fi
}

while true ; do
  main
done

bailout

# EOF #
