#!/bin/zsh

# if we wanted to shift through all settings in xrandr order
order=(normal left inverted right)

# but if we just want to toggle between two:
order=(normal right)

wacom_names=(none ccw half cw)
xrandr_order=(normal left inverted right)
old=$xrandr_order[1]
if [ -e /dev/shm/rotation ]
then
	old=`cat /dev/shm/rotation`
fi


function rotate()
{
	# shift until we're at the current if its on the list
	z=();
	while [ $#order > 0 -a $order[1] != $old ]
	do
		z=($z $order[1]);
		shift order;
	done

	# if not found, just reset the list
	#
	if [ $#order = 0 ] 
	then
		order=($z)
		return
	fi

	order=($order $z)

	for ((x=0;x<$1;x++))
	do
		t=$order[1];
		shift order
		order=($order $t)
	done
}
function all_rotate()
{
	order=($xrandr_order)
	rotate $*
}

function reorient()
{
	orientation=$1
	topx=0
	topy=0
	bottomx=9600
	bottomy=7200
	swap=0
	invert_x=0
	invert_y=0

	real_topx=0
	real_topy=0
	real_bottomx=9600
	real_bottomy=7200


	case $orientation in
		[0-3] )
			reorient $xrandr_order[`expr $orientation + 1`]
		;;
		normal | untablet )
			wacom=1
			orientation=normal
			swap=0
			invert_x=0
			invert_y=0
		;;
		left )
			wacom=2
			swap=1
			invert_x=1
			invert_y=0
			tmp=$bottomy
			bottomy=$bottomx
			bottomx=$tmp
			orientation=left
		;;
		inverted )
			wacom=3
			swap=0
			invert_x=1
			invert_y=1
		;;
		right | tablet )
			wacom=4
			swap=1
			invert_x=0
			invert_y=1
			tmp=$bottomy
			bottomy=$bottomx
			bottomx=$tmp
			orientation=right
		;;
		180 )
			all_rotate 2;
			reorient $order[1];
			return;
		;;
		ccw )
			all_rotate 1;
			reorient $order[1];
			return
		;;
		cw )
			all_rotate `expr $#xrandr_order - 1`
			reorient $order[1];
			return
		;;
		next )
			rotate 1;
			reorient $order[1];
			return
		;;
		prev )
			rotate `expr $#order - 1`
			reorient $order[1];
			return
		;;
		* )
			return
		;;
	esac

	if [ $old != $orientation -o 1 ]
	then
		xrandr -o $orientation
		for dev in `xinput list | grep N-Trig | grep pointer | grep slave | cut -c 55-56`
		do
			case `xinput list-props "$dev" |& grep "Evdev\|Wacom" | head -1 | sed 's/^\s//' | cut -f 1 -d ' '` in
				Evdev )
					xinput set-prop "$dev" "Evdev Axes Swap" $swap
					xinput set-prop "$dev" "Evdev Axis Inversion" $invert_x $invert_y
					xinput set-prop "$dev" "Evdev Axis Calibration" $topx $bottomx $topy $bottomy
				;;
				Wacom )
					xsetwacom set "$dev" rotate $wacom_names[$wacom]
				;;
			esac
		done
#		if [ `ps -u $USER | grep -c easystroke` -gt 0 ]
#		then
#			pkill easystroke
#			easystroke &
#		fi
	else
		print "orientation is $orientation\n";
	fi

	echo $orientation > /dev/shm/rotation

}

reorient $1
