#!/bin/bash
# This script rotates the screen and touchscreen input 90 degrees each time it is called, 
# also disables the touchpad, and enables the virtual keyboard accordingly
# Original by Ruben Barkow: https://gist.github.com/rubo77/daa262e0229f6e398766

## Changings/Adds by Jörg Reinholz, Kassel (Germany)
# Disable keyboard and/or touchpad in 'upside down'- and '90°'-modes
# Added debug option
# Added settings for Lenovo YOGA 300-11IBY
# Prepared for other machines
# the screen for xrandr ist now defined (its a litte faster)

#########################
#     DEBUG-Option      #
#########################

debug=0; # set only to 1 for developing
if [ 1 -eq $debug ];
	then set -x;
else
	set +x;
fi

#########################
#     Configuration     #
#########################

#### At least one (or all) of the next 3 option should by enabbled! 1 = on / 0 = off
manageOnboard=1;   # Set to 1 to start the program `onboard` in 'upside down' and '90°'-modes (and stop in normal-modus)
manageKeyboard=1;  # Set to 1 to disable the keyboard in 'upside down'- and '90°'-modes (and enable in normal-modus)
manageTouchpad=1;  # Set to 1 to disable the touchpad in 'upside down'- and '90°'-modes  (and enable in normal-modus)

### You can safe your XFCE4-Panel-settings with `xfpanel-settings` and use them:
manageXFCE4Panel=0; # 1 = on / 0 = off
# Edit the path to your files with XFCE-Settings
normalPanel='/path/to/normal.panel.tar.bz2';
invertedPanel='/path/to/touch.panel.tar.bz2';
leftPanel='/path/to/touch.panel.tar.bz2';
###

### show xrandr for your screen, but in most cases is this the first (and only) screen:
screen=0;

#### Settings for the machine(s) - show `xinput list` to find your settings.
# You can use Regexes for grep -Pi 
touchscreensRegex='Touchscreen|ATML';                                     # Extended Regex! Show `man grep`.
touchpadsRegex='Touchpad|Synaptics TM|Wacom.*Finger.*touch';              # Extended Regex! Show `man grep` .
keyboardDevices=('AT Translated Set 2 keyboard' 'Ideapad extra buttons'); # Array! see `man bash`.

########################################
#             Program                  #
########################################

LANG="c"; # Hint: Do not translate outputs if you "parse" thiss stuff!

if [ 1 -eq $manageXFCE4Panel ]; then
	if [ ! -x '/usr/bin/xfpanel-switch' ] || [ ! -r "$invertedPanel" ] || [ ! -r "$normalPanel" ] || [ ! -r "$leftPanel" ] || [ ! -r "$rightPanel" ] ; then
		manageXFCE4Panel=0;
	fi
fi

if [ "$1" = '--help'  ] || [ "$1" = '-h'  ] ; then
	echo 'Usage: rotate-screen.sh [OPTION]';
	echo ;
	echo 'This script rotates the screen and touchscreen input 90 degrees each time it is called,';
	echo 'also disables the touchpad, and enables the virtual keyboard accordingly';
	echo ;
	echo 'Usage:';
	echo ' -h --help display this help';
	echo ' -j (just horizontal) rotates the screen and touchscreen input only 180 degrees';
	echo ' -n always rotates the screen back to normal';
	exit 0
fi

t=$(xinput list | grep -Pi "$touchscreensRegex" | tr -d '[[⎜↳]]'| sed -Ee 's/[ \t]+/ /g' | sed -Ee 's/id=.*$//');
TouchscreenDevice=$(echo -n $t); #trim

if [ 1 -eq $manageTouchpad ]; then
	t=$(xinput list | grep -Pi "$touchpadsRegex" | tr -d '[[⎜↳]]' | sed -Ee 's/[ \t]+/ /g' | sed -Ee 's/id=.*$//');
	TouchpadDevice=$(echo -n $t); # trim
fi

if [ 1 -eq $manageOnboard ]; then
	if [ 1 -lt $(ps ax | grep 'onboard' | wc -l) ]; then
		onboardRunning=1;
	else
		onboardRunning=0;
	fi
fi

touchpadEnabled=$(xinput --list-props "$TouchpadDevice" | awk '/Device Enabled/{print $NF}');
screenMatrix=$(xinput --list-props "$TouchscreenDevice" | awk '/Coordinate Transformation Matrix/{print $5$6$7$8$9$10$11$12$NF}' | sed -Ee 's/\.[0-9]+//g' -e 's/,/ /g');

normal='1 0 0 0 1 0 0 0 1';
inverted='-1 0 1 0 -1 1 0 0 1';
left='0 -1 1 1 0 0 0 0 1';
right='0 1 0 -1 0 1 0 0 1';

if [ "$screenMatrix" = "$normal" ] && [ "$1" != '-n' ]; then
	if [ 1 -eq $debug ];
		then echo 'Upside down:';
	fi
	xrandr --screen $screen -o inverted;
	xinput set-prop "$TouchscreenDevice" 'Coordinate Transformation Matrix' $inverted;
	xinput disable "$TouchpadDevice";
	if [ 0 -eq $onboardRunning ]; then
		onboard &
	fi
	if [ 1 -eq $manageOnboard ] && [ 1 -eq $manageKeyboard ]; then
		for device in "${keyboardDevices[@]}"; do
			xinput --set-prop "$device" 'Device Enabled' 0;
		done
	fi
	if [ 1 -eq $manageXFCE4Panel ]; then
		xfpanel-switch load "$invertedPanel";
	fi
elif [ "$screenMatrix" = "$inverted" ] && [ "$1" != '-j' ] && [ "$1" != '-n' ]; then
	if [ 1 -eq $debug ]; then
		echo '90° to the left';
	fi
	xrandr --screen $screen -o left;
	xinput set-prop "$TouchscreenDevice" 'Coordinate Transformation Matrix' $left;
	xinput disable "$TouchpadDevice";
	if [ 1 -eq $manageOnboard ] && [ 0 -eq $onboardRunning ]; then
		onboard &
	fi
	if [ 1 -eq $manageKeyboard ]; then
		for device in "${keyboardDevices[@]}"; do
			xinput --set-prop "$device" 'Device Enabled' 0;
		done
	fi
	if [ 1 -eq $manageXFCE4Panel ]; then
		xfpanel-switch load "$leftPanel";
	fi
else 
    if [ 1 -eq $debug ]; then
		echo "Back to normal";
	fi
	xrandr --screen $screen -o normal;
	xinput set-prop "$TouchscreenDevice" 'Coordinate Transformation Matrix' $normal;
	xinput enable "$TouchpadDevice";
	if [ 1 -eq $manageOnboard ] &&  [ 1 -eq $onboardRunning ]; then
		killall onboard;
	fi
	if [ 1 -eq $manageKeyboard ]; then
		for device in "${keyboardDevices[@]}"; do
			xinput --set-prop "$device" 'Device Enabled' 1;
		done
	fi
	if [ 1 -eq $manageXFCE4Panel ]; then
		xfpanel-switch load "$normalPanel";
	fi
fi
