#/bin/sh
cmd=$1
state=~/.screen.state
stamp=`test -e $state && stat -c "%Y" $state`
now=`date +%s`
touch $state
# avoid repeated invocation
if [ "$stamp" = "$now" ]; then
  echo "do nothing"
  exit
fi
xrandr -q|grep -e '\(VGA\|LVDS\|\*\|+$\)' > $state
both=`cat $state|grep '\*'|wc|xargs|cut -d\  -f1|grep -q 2 && echo 1`
lcd=`cat $state|tail -n1|grep -q '\*' && echo 1`
res=`cat $state|grep '+$'|sed -e 's/^ *\([0-9]*x[0-9]*\).*$/\1/'`
lcdres=`echo $res|cut -d\  -f2`
vgares=`echo $res|cut -d\  -f1`
if [ "$cmd" = "rotate" ]; then
  if [ "$both" = 1 ]; then
    cmd="lcd"
  else
    if [ "$lcd" = 1 ]; then
      cmd="vga"
    else
      cmd="both"
    fi
  fi
fi
echo $cmd    
if [ "$cmd" = "both" ]; then
  xrandr --output LVDS --mode $lcdres --auto
  xrandr --output VGA  --mode $vgares --below LVDS --auto
fi

if [ "$cmd" = "vga" ]; then
  xrandr --output LVDS --off
  xrandr --output VGA  --mode $vgares --auto 
fi

if [ "$cmd" = "lcd" ]; then
  xrandr --output VGA  --off
  xrandr --output LVDS --mode $lcdres --auto
fi
touch $state

