#!/bin/bash

# omarchy:summary=Reset the trackpad by unbinding and rebinding its driver.
# omarchy:requires-sudo=true

# Only reset I2C HID devices that udev marks as a touchpad, so the keyboard and
# touchscreen sharing the i2c_hid_acpi driver are left alone.
is_touchpad() {
  local input

  for input in "$1"/*/input/input*; do
    if udevadm info --query=property "$input" 2>/dev/null | grep -qx "ID_INPUT_TOUCHPAD=1"; then
      return 0
    fi
  done

  return 1
}

echo "Releasing the trackpad in Hyprland..."
omarchy-toggle-input-device touchpad cycle

driver="${OMARCHY_I2C_HID_DRIVER_PATH:-/sys/bus/i2c/drivers/i2c_hid_acpi}"

for dev in "$driver"/i2c-*; do
  [[ -e $dev ]] || continue
  is_touchpad "$dev" || continue

  I2C_DEVICE=$(basename "$dev")
  echo "Resetting $I2C_DEVICE via i2c_hid_acpi unbind/rebind..."
  echo "$I2C_DEVICE" | sudo tee "$driver/unbind" > /dev/null
  sleep 1
  echo "$I2C_DEVICE" | sudo tee "$driver/bind" > /dev/null
  echo "Done"
done

# Also try THC path
if lsmod | grep -q intel_quicki2c; then
  echo "Reloading intel_quicki2c..."
  sudo modprobe -r intel_quicki2c && sudo modprobe intel_quicki2c
fi
