#!/bin/bash

# omarchy:summary=Print the detected Hyprland touchpad or trackpad device name

mice=$(hyprctl devices -j | jq -r '.mice[].name')
# iptsd (Surface touchpads) takes the raw device and creates its own, which is
# the one that moves the pointer. The raw one stays silent, so disabling it
# would leave the touchpad working.
device=""
shopt -s nocasematch
while IFS= read -r mouse; do
  if [[ $mouse == iptsd-virtual-touchpad* ]]; then
    device=$mouse
    break
  fi
  if [[ -z $device && $mouse =~ touchpad|trackpad ]]; then
    device=$mouse
  fi
done <<<"$mice"
shopt -u nocasematch

is_udev_touchpad() {
  local event="$1" dev_id data line
  if [[ -r $event/dev ]] && read -r dev_id <"$event/dev"; then
    data="$udev_data_path/c$dev_id"
    if [[ -r $data ]]; then
      while IFS= read -r line; do
        [[ $line == "E:ID_INPUT_TOUCHPAD=1" ]] && return 0
      done <"$data"
      return 1
    fi
  fi
  udevadm info --query=property "$event" 2>/dev/null | grep -Fxq 'ID_INPUT_TOUCHPAD=1'
}

# Some touchpads carry neither word (Apple Silicon's is "apple-mtp-multi-touch"),
# so ask udev which mouse is one. The name alone can't say: some touchscreens'
# mouse interfaces are called multi-touch too.
if [[ -z $device ]]; then
  input_class="${OMARCHY_INPUT_CLASS_PATH:-/sys/class/input}"
  udev_data_path="${OMARCHY_UDEV_DATA_PATH:-/run/udev/data}"
  for event in "$input_class"/event*; do
    [[ -r $event/device/name ]] || continue
    # Hyprland's name for a device: the kernel's, lowercased, with spaces,
    # commas and newlines as dashes, and -1, -2 and so on after a name another
    # device already took.
    name=$(<"$event/device/name")
    name=${name,,}
    name=${name//[ ,$'\n']/-}
    # Match the name first: reading udev data only for matching mouse nodes
    # avoids scanning every keyboard, button and switch on each menu open.
    match=""
    while IFS= read -r mouse; do
      if [[ $mouse == "$name" || ( $mouse == "$name"-* && ${mouse#"$name"-} =~ ^[0-9]+$ ) ]]; then
        match=$mouse
        break
      fi
    done <<<"$mice"
    [[ -n $match ]] || continue
    is_udev_touchpad "$event" || continue
    device=$match
    break
  done
fi

[[ -n $device ]] && echo "$device"
