#!/bin/sh

set -e

ACCDEV="/sys/bus/iio/devices/iio:device0"
DIR="right"
OLDDIR="$DIR"


rotate()
{
	case $1 in
		normal)
			matrix="0 -1 1 1 0 0 0 0 1"
			;;
		inverted)
			matrix="0 1 0 -1 0 1 0 0 1"
			;;
		left)
			matrix="-1 0 1 0 -1 1 0 0 1"
			;;
		right)
			matrix="1 0 0 0 1 0 0 0 1"
			;;
		*)
			echo "rotate(): wrong arg: $1"
			exit 1
			;;
	esac
	xrandr --output LVDS-1 --rotate $1
	xinput set-prop elan-touchscreen 'Coordinate Transformation Matrix' $matrix
}

while true; do
	read running < /sys/bus/iio/devices/iio:device0/buffer/enable
	[ "$running" = 1 ] || exit 0

	read X < $ACCDEV/in_accel_x_raw
	read Y < $ACCDEV/in_accel_y_raw
	if [ "$X" -gt "12000" ]; then
		DIR="normal"
	fi
	if [ "$X" -lt "-12000" ]; then
		DIR="inverted"
	fi
	if [ "$Y" -gt "12000" ]; then
		DIR="right"
	fi
	if [ "$Y" -lt "-12000" ]; then
		DIR="left"
	fi
	if [ "$OLDDIR" != "$DIR" ]; then
		rotate "$DIR"
	fi
	OLDDIR="$DIR"
	sleep 1
done
