#!/bin/sh

ORIENTATION=""
TMPFILE=$(mktemp /tmp/autorotate.XXXXXX)

cleanup () {
	rm $TMPFILE
}

trap cleanup EXIT

adjust_pen () {
		local pen="GXTP7386:00 27C6:0113 Stylus Pen (0)"
		[ -z "$ORIENTATION" ] && ORIENTATION=$(<"$TMPFILE")
		case "$ORIENTATION" in
        bottom-up)
                xinput set-prop "$pen" 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1;;
        normal)
                xinput set-prop "$pen" 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1;;
        right-up)
                xinput set-prop "$pen" 'Coordinate Transformation Matrix' 0 1 0 -1 0 1 0 0 1;;
        left-up)
                xinput set-prop "$pen" 'Coordinate Transformation Matrix' 0 -1 1 1 0 0 0 0 1;;
        *)
                ;;
        esac
}

adjust_touchscreen () {
		local touchscreen="GXTP7386:00 27C6:0113"
		case "$ORIENTATION" in
	    bottom-up)
	        xinput set-prop "$touchscreen" 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1;;
	    normal)
	        xinput set-prop "$touchscreen" 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1;;
	    right-up)
	        xinput set-prop "$touchscreen" 'Coordinate Transformation Matrix' 0 1 0 -1 0 1 0 0 1;;
	    left-up)
	        xinput set-prop "$touchscreen" 'Coordinate Transformation Matrix' 0 -1 1 1 0 0 0 0 1;;
        *)
                ;;
	    esac
}

adjust_screen () {
		local int_out="eDP-1"
		case "$ORIENTATION" in
	    bottom-up)
	        xrandr --output "$int_out" --rotate normal;;
	    normal)
	        xrandr --output "$int_out" --rotate inverted;;
	    right-up)
	        xrandr --output "$int_out" --rotate right;;
	    left-up)
	        xrandr --output "$int_out" --rotate left;;
        *)
                ;;
	    esac
}

XLOG="/var/log/Xorg.0.log"
ADDPENSTR="Adding extended input device \"GXTP7386:00 27C6:0113 Stylus Pen (0)\""
tail -f $XLOG | grep -m 1 "$ADDPENSTR" && adjust_pen &

monitor-sensor |
	while read line
	do
	    word=$(echo $line | grep 'orientation' | tail -1 | grep -oE '[^ ]+$')
		case "$word" in
	    bottom-up|normal|right-up|left-up)
				ORIENTATION="$word"
				echo $ORIENTATION > $TMPFILE
				echo "Rotating $ORIENTATION"
				adjust_screen
				adjust_touchscreen
				adjust_pen
				;;
        *)
                ;;
	    esac
	done

