#!/bin/bash
# 251205 radky: toggle current touchpad state (on/off)
# based on touchpad-toggle.sh by wizard of Puppy Linux

# define current touchpad state (on=0 off=1)
grep -B5 'mouse[0-5]' /proc/bus/input/devices | \
grep -E 'Name=|Sysfs=|Handlers=' | \
grep -A2 -Ei 'touchpad|synap|alps|elan|etps' | grep -v '--' -- > /tmp/mouse_devices.txt
grep -A2 -i 'trackpoint' /tmp/mouse_devices.txt | grep 'Sysfs=' | cut -d'=' -f2 | tr -d '\n' > /tmp/mouse_trackpoint.txt
grep -A2 -i 'stick' /tmp/mouse_devices.txt | grep 'Sysfs=' | cut -d'=' -f2 | tr -d '\n' > /tmp/mouse_stick.txt
sysfs=$(cat /tmp/mouse_devices.txt | \
	grep -vf /tmp/mouse_trackpoint.txt | \
	grep -vf /tmp/mouse_stick.txt | \
	grep 'Sysfs=' | cut -d'=' -f2)
sysfs="${sysfs#/}"
device=/sys/$sysfs/inhibited
touchpadstate=$(cat $device)

# assign touchpad image to GUI
[ -z "$touchpadstate" ] && touchpadstate=""
if [[ $touchpadstate == '1' ]]; then
	IMAGE="/usr/share/icons/touchpad_on.png"
elif [[ $touchpadstate == '0' ]]; then
	IMAGE="/usr/share/icons/touchpad_off.png"
else
	IMAGE="/usr/share/icons/touchpad_error.png"
fi

# toggle current touchpad state
if [[ $touchpadstate == '1' ]]; then
   echo 0 > $device # toggle off to on
   yad 2>/dev/null --title="Touchpad Toggle" \
       --borders=20 \
       --center \
       --image="$IMAGE" \
       --text " \n          <b>Touchpad toggled ON</b>          \n" \
       --no-buttons \
       --timeout 2
elif [[ $touchpadstate == '0' ]]; then
   echo 1 > $device # toggle on to off
   yad 2>/dev/null --title="Touchpad Toggle" \
       --borders=20 \
       --center \
       --image="$IMAGE" \
       --text " \n          <b>Touchpad toggled OFF</b>          \n" \
       --no-buttons \
       --timeout 2
else
   yad 2>/dev/null --title="Touchpad Toggle" \
       --borders=20 \
       --center \
       --image="$IMAGE" \
       --text " \n          <b>Touchpad not found</b>          \n" \
       --no-buttons \
       --timeout 2
fi   

rm -f /tmp/mouse*.txt

exit
