#!/bin/bash
# https://www.knapp80ps.de/miixrotatescreen
# November 2019 - Tested and found working on Lenovo Das IdeaPad Miix 320 10ICR Convertible Laptop with Xubuntu 19.10 and XFCE 4.14 
# This is the Lenovo IdeaPad Miix 320 versions of the script from the original script:
# https://github.com/julienw/config-files/blob/master/yoga/rotate-screen.sh
# This is a bash script to make screen autorotation possible based on device orientation.
# All you need for this script to run  iio-sensor-proxy ($sudo apt install iio-sensor-proxy)
# Nowdays, iio-sensor-proxy usually is included in any Linux Distro.
# PS: Gnome has a built in implementation of auto screen rotation based on iio-sensor-proxy already. 
#
# Original Source Code: https://linuxappfinder.com/blog/auto_screen_rotation_in_ubuntu
#
# Receives input from monitor-sensor (part of iio-sensor-proxy package). You can run monitor-sensor first in command line to verify correct working.
# This script could be added to startup applications for the user.

# Sensor pipe to get output from monitor-sensor
sensorpipe=/tmp/pivotsensor

# if pipe doesn't exist, create it
if [[ ! -p $sensorpipe ]]; then
   /usr/bin/mkfifo $sensorpipe
fi
/usr/bin/logger "autorotate started" 
/usr/bin/monitor-sensor >> $sensorpipe 2>&1 & #
monisenspid=$!
# Parse output or monitor sensor to get the new orientation whenever a line appaers in sensorpipe
# Possibles are: normal, bottom-up, right-up, left-up, quit. Light data will be ignored
while true; do
   if read line<$sensorpipe; then
      #echo $line
      ORIENTATION=$(/usr/bin/echo $line | /usr/bin/grep 'orientation' | /usr/bin/grep -oE '[^ ]+$')  # Read the last line that was added to the file and get the orientation
      case "$ORIENTATION" in # Set the actions to be taken for each possible orientation
         normal)
            /usr/bin/xrandr -o normal
            /usr/bin/xinput set-prop "FTSC1000:00 2808:1015" "Coordinate Transformation Matrix" 1 0 0 0 1 0 0 0 1 
            ;;
         bottom-up)
            /usr/bin/xrandr -o inverted
            /usr/bin/xinput set-prop "FTSC1000:00 2808:1015" "Coordinate Transformation Matrix" -1 0 1 0 -1 1 0 0 1 
            ;;
         right-up)
            /usr/bin/xrandr -o right
            /usr/bin/xinput set-prop "FTSC1000:00 2808:1015" "Coordinate Transformation Matrix" 0 1 0 -1 0 1 0 0 1 
            ;;
         left-up)
            /usr/bin/xrandr -o left
            /usr/bin/xinput set-prop "FTSC1000:00 2808:1015" "Coordinate Transformation Matrix" 0 -1 1 1 0 0 0 0 1 
            ;;
         quit)  # if you send "orientation quit" to the pipe, the script exits
            break ;;   
      esac
   fi
done
/usr/bin/rm -f $sensorpipe
#/usr/bin/killall monitor-sensor
/usr/bin/kill $monisenspid
/usr/bin/logger "autorotate ended"
exit 0

