#!/bin/bash
path="/sys/bus/iio/devices/iio:device5" #Path is not fixed! So use workaround below, which is correct
# path="/sys/devices/pci0000:00/0000:00:14.0/usb2/2-4/2-4:1.0/*0483:91D1*/HID-SENSOR-200073.1.auto/iio:device?"
margin=500000
current="none"

accel_x=`find -L /sys/bus/iio/devices -maxdepth 2 -name in_accel_x_raw`
accel_y=`find -L /sys/bus/iio/devices -maxdepth 2 -name in_accel_y_raw`
accel_z=`find -L /sys/bus/iio/devices -maxdepth 2 -name in_accel_z_raw`

stylus="Wacom HID 48CA Pen stylus"
touch="Wacom HID 48CA Finger touch"
eraser="Wacom HID 48CA Pen eraser"

while true; do

  x=`cat $accel_x`
  y=`cat $accel_y`
  z=`cat $accel_z`

oldcurrent=$current

if [[ $x -gt -$margin ]] && [[ $x -lt $margin ]]; then
    if [[ "$y" -gt "$margin" ]]; then
        if [[ $current != "half" ]]; then
            xrandr -o inverted
            xsetwacom set "$stylus" Rotate half
            xsetwacom set "$eraser" Rotate half
            xsetwacom set "$touch" Rotate half
            current="half"
        fi
    elif [[ "$y" -lt "-$margin" ]]; then
        if [[ $current != "none" ]]; then
            xrandr -o normal
            xsetwacom set "$stylus" Rotate none
            xsetwacom set "$eraser" Rotate none
            xsetwacom set "$touch" Rotate none
            current="none"
        fi
    fi
elif [[ "$x" -gt "0" ]]; then
    if [[ $current != "ccw" ]]; then
        xrandr -o left
        xsetwacom set "$stylus" Rotate ccw
        xsetwacom set "$eraser" Rotate ccw
        xsetwacom set "$touch" Rotate ccw
        current="ccw"
    fi
else
    if [[ $current != "cw" ]]; then
        xrandr -o right
        xsetwacom set "$stylus" Rotate cw
        xsetwacom set "$eraser" Rotate cw
        xsetwacom set "$touch" Rotate cw
        current="cw"
    fi
fi

  if [[ $oldcurrent != $current ]]; then
      repicom
      if [[ $current == "cw" ]] || [[ $current == "ccw" ]]; then
          panel 1060 &
          hsetroot -center /home/maxx/.config/bspwm/cat_vertical.png
          sleep 0.5
          retray 760 &
      else
          panel &
          hsetroot -tile /home/maxx/.config/bspwm/cat.png
          sleep 0.5
          retray &
      fi
  fi

  sleep 0.5
done
