#!/bin/sh

if ! pgrep -x labwc > /dev/null ; then
  exit 0
fi

if grep -qs "touch.*mouseEmulation" ~/.config/labwc/rc.xml ; then
  exit 0
fi

TOUCH=$(libinput list-devices | tr \\n @ | sed 's/@@/\\\n/g' | grep "Capabilities:.*touch" | sed 's/Device:[ \\\t]*//' | cut -d @ -f 1)
if [ -z "$TOUCH" ] ; then
  exit 0
fi
NTOUCH=$(echo "$TOUCH" | wc -l)

DISPLAY=$(wlr-randr | grep ^\\S | cut -d ' ' -f 1)
if [ -z "$DISPLAY" ] ; then
  exit 0
fi
NDISPLAY=$(echo "$DISPLAY" | wc -l)

if [ $NDISPLAY -eq 1 ] && [ $NTOUCH -eq 1 ] ; then
  if [ -e ~/.config/labwc/rc.xml ] ; then 
    cp ~/.config/labwc/rc.xml ~/.config/labwc/rc.bak
    xmlstarlet ed --subnode "/_:openbox_config" -t elem -n "touch"  ~/.config/labwc/rc.bak | \
    xmlstarlet ed --insert "/_:openbox_config/_:touch" -t attr -n "deviceName" -v "$TOUCH" | \
    xmlstarlet ed --insert "/_:openbox_config/_:touch" -t attr -n "mapToOutput" -v "$DISPLAY" | \
    xmlstarlet ed --insert "/_:openbox_config/_:touch" -t attr -n "mouseEmulation" -v "yes" > ~/.config/labwc/rc.xml
  else
    mkdir -p ~/.config/labwc/
    echo "<?xml version=\"1.0\"?>\n<openbox_config xmlns=\"http://openbox.org/3.4/rc\">\n\t<touch deviceName=\"$TOUCH\" mapToOutput=\"$DISPLAY\" mouseEmulation=\"yes\"/>\n</openbox_config>" > ~/.config/labwc/rc.xml
  fi
  labwc --reconfigure
fi

