#!/bin/sh
ROTATION=`sconfig rotation`
X_PHYSCAL_MM=`xconfig getattribute -p /variables/display -n xphys_mm`
Y_PHYSCAL_MM=`xconfig getattribute -p /variables/display -n yphys_mm`

case "${ROTATION}" in
	90)
		ORIENTATION="left"
		COORD_MATRIX="0 -1 1 1 0 0 0 0 1"
		;;
	180)
		ORIENTATION="inverted"
		COORD_MATRIX="-1 0 1 0 -1 1 0 0 1"
		;;
	270)
		ORIENTATION="right"
		COORD_MATRIX="0 1 0 -1 0 1 0 0 1"
		;;
	*)
		ORIENTATION="normal"
		COORD_MATRIX="1 0 0 0 1 0 0 0 1"
		;;
esac

# Set screen size
if [ ! -z "$X_PHYSCAL_MM" ]
then
	if [ ! -z "$Y_PHYSCAL_MM" ]
	then
		# the fbmm parameter does only work in normal orienation, so first turn to normal, adapt the size and turn back
		xrandr -o normal
		case "${ROTATION}" in
		90|270)
			xrandr --fbmm "$Y_PHYSCAL_MM"x"$X_PHYSCAL_MM"
			;;
		*)
			xrandr --fbmm "$X_PHYSCAL_MM"x"$Y_PHYSCAL_MM"
			;;
		esac
	fi
fi

# Rotate display
xrandr -o ${ORIENTATION}

xinput_calibrator --list | sed 's/Device "\([^"]*\)".*/\1/' | while read touch
do
	if [ "$touch" != "tslib" ]
	then
		xinput set-prop "$touch"  "Coordinate Transformation Matrix" ${COORD_MATRIX}
	fi
done

