#!/bin/sh
set -e

ROTATION_FILE="$HOME/.rotation"
SCREEN="$1"

_core(){
	case "$1" in
	1)	xrandr --output "$SCREEN" --rotate normal	;;
	2)	xrandr --output "$SCREEN" --rotate left	;;
	3)	xrandr --output "$SCREEN" --rotate inverted	;;
	4)	xrandr --output "$SCREEN" --rotate right	;;
	*)	return 1
	esac
	return 0
}

if [ -e "$ROTATION_FILE" ]
then	ROTATION="$(dd <"$ROTATION_FILE" 2>/dev/null)"
	if ! _core "$ROTATION"
	then	_core 1
		ROTATION=2
	else	ROTATION=$(printf "%s + 1\n" "$ROTATION" | bc)
		! [ "$ROTATION" -gt 4 ] \
			|| ROTATION=1
	fi
else	_core 1
	ROTATION=2
fi

printf "%s\n" "$ROTATION" >"$ROTATION_FILE"

exit 0
