#!/bin/sh
# Rotates the XO screen 90 degrees on every invocation

# fifo where commands to rotate the touchpad may be written
CMD_FIFO=/var/run/olpc-kbdshim_command

# handle ebook/normal inversion
case $1 in
-e) echo Z >$CMD_FIFO; exit 0;;
-n) echo z >$CMD_FIFO; exit 0;;
-*) echo "usage: $0 [-e|-n]" >&2 ; exit 1;;
esac

get_x_credentials()
{
    # fetch the local X server's XAUTHORITY variable
    eval "$( xargs -n 1 -0 < /proc/$(pidof X)/environ | grep '^XAUTHORITY=')"
    export XAUTHORITY
    export DISPLAY=:0

}

test "$XAUTHORITY" || get_x_credentials

# get current screen orientation
if ! xrandrout=$(xrandr -q)
then
    echo xrandr query failed >&2
    exit 1
fi

now=$(echo $xrandrout | sed -n 's/.*[0-9] \([a-z]*\) *(.*/\1/p')


# note: on F9-based OLPC releases, the xorg-x11-drv-geode library
# rotated the screen the wrong way (version 2.10 and earlier).
# for those systems, the following case should read:
# case $now in
#   left)       new=normal;;
#   inverted)   new=left;;
#   right)      new=inverted;;
#   ""|normal)  new=right;;
#   *)          new=normal;;
# esac

case $now in
left)       new=inverted;;
inverted)   new=right;;
right)      new=normal;;
""|normal)  new=left;;
*)          new=normal;;
esac

xrandr -o $new && test -e $CMD_FIFO && echo $new >$CMD_FIFO
