Detecting keyboard removal on Miix 320 and adapting a script

Hi all,
olek has done a great job adapting mate to the lenovo miix 320, and I thank him for it.
In particular, this script is purposed to rotate the display when the screen is turned:

# Auto rotate screen based on device orientation

# Receives input from monitor-sensor (part of iio-sensor-proxy package)
# Screen orientation and launcher location is set based upon accelerometer position
# Launcher will be on the left in a landscape orientation and on the bottom in a portrait orientation
# This script should be added to startup applications for the user

# Clear sensor.log so it doesn't get too long over time
> /tmp/sensor.log

# Launch monitor-sensor and store the output in a variable that can be parsed by the rest of the script
monitor-sensor >> /tmp/sensor.log 2>&1 &

# Parse output or monitor sensor to get the new orientation whenever the log file is updated
# Possibles are: normal, bottom-up, right-up, left-up
# Light data will be ignored
while inotifywait -e modify /tmp/sensor.log; do
# Read the last line that was added to the file and get the orientation
ORIENTATION=$(tail -n 1 /tmp/sensor.log | grep 'orientation' | grep -oE '[^ ]+

# Set the actions to be taken for each possible orientation
case "$ORIENTATION" in
xrandr --output DSI-1 --rotate right && xinput set-prop "FTSC1000:00 2808:1015" 'Coordinate Transformation Matrix' 0 1 0 -1 0 1 0 0 1;;
xrandr --output DSI-1 --rotate inverted && xinput set-prop "FTSC1000:00 2808:1015" 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1;;
xrandr --output DSI-1 --rotate normal && xinput set-prop "FTSC1000:00 2808:1015" 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1;;
xrandr --output DSI-1 --rotate left && xinput set-prop "FTSC1000:00 2808:1015" 'Coordinate Transformation Matrix' 0 -1 1 1 0 0 0 0 1;;
xinput disable "FTSC1000:00 2808:1015" && xinput enable "FTSC1000:00 2808:1015"
#killall caja

Very useful in tablet mode, but annoying in laptop mode. To be even better, it would need to get active only when the keyboard is detached from the screen, do nothing when keyboard is attached.

It must not be very hard for someone used to writing scripts. Impossible for me.

Can you help? Thanks in advance.