#!/bin/sh

# This script is for X sessions. I don't know how this would
# work in wayland. I don't need to worry about that anytime
# soon.

orientation="$(xrandr -q | grep -v dis | grep connected | awk '{print $5}' | sed 's:(::')"
displayName="$(xrandr -q | grep -v dis | grep connected | awk '{print $1}')"
stylusDeviceIds="$(xinput --list | grep Stylus | grep pointer | cut -d '=' -f 2 | cut -f 1)"
matrix="-1 0 1 0 -1 1 0 0 1"

xinput --disable "IPTS Touch"

for id in ${stylusDeviceIds} ; do
	xinput --disable ${id}
	xinput --enable ${id}
done

if [ "${orientation}" != "inverted" ] ; then
	xrandr --output "${displayName}" --rotate inverted
	xinput set-prop "IPTS Touch" --type=float \
		"Coordinate Transformation Matrix" ${matrix}
	xinput set-prop "Microsoft Surface Keyboard Mouse" --type=float \
		"Coordinate Transformation Matrix" ${matrix}
	xinput set-prop "Microsoft Surface Keyboard Touchpad" --type=float \
		"Coordinate Transformation Matrix" ${matrix}
	for id in ${stylusDeviceIds} ; do
		xinput set-prop ${id} --type=float \
			"Coordinate Transformation Matrix" ${matrix}
	done
fi
