#!/usr/bin/env bash
set -o errexit
set -o pipefail

main() {
  local session_id
  session_id="$(loginctl --output=json | jq -r '.[]|.session')"

  local session_type
  session_type="$(
    loginctl show-session "${session_id}" -p Type |
      awk -F= '{ print $2 }'
  )"

  "_setup_elan_touchpad_${session_type}"
  "_setup_trackman_marble_${session_type}"
}

_setup_elan_touchpad_wayland() {
  local tp='org.gnome.desktop.peripherals.touchpad'
  gsettings set "${tp}" natural-scroll true
  gsettings set "${tp}" tap-to-click true
}

_setup_trackman_marble_wayland() {
  local tm='org.gnome.desktop.peripherals.trackball'
  gsettings set "${tm}" scroll-wheel-emulation-button 8
  gsettings set "${tm}" accel-profile default
}

_setup_elan_touchpad_x11() {
  local etp='Elan Touchpad'

  if ! xinput list-props "${etp}" &>/dev/null; then
    return
  fi
  xinput set-prop "${etp}" 'libinput Tapping Enabled' 1
  xinput set-prop "${etp}" 'libinput Natural Scrolling Enabled' 1
}

_setup_trackman_marble_x11() {
  local tmm='Logitech USB Trackball'

  if ! xinput list-props "${tmm}" &>/dev/null; then
    return
  fi
  xinput set-prop "${tmm}" 'libinput Button Scrolling Button' 8
  xinput set-prop "${tmm}" 'libinput Scroll Method Enabled' 0 0 1
}

main "${@}"
