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

main() {
  export RUNNING_AS="${RUNNING_AS:-dan}"
  RUNNING_AS_ID="$(id -u "${RUNNING_AS}")"
  export RUNNING_AS_ID

  export XINPUT_EXE="${XINPUT_EXE:=xinput}"
  export XAUTHORITY="/run/user/${RUNNING_AS_ID}/gdm/Xauthority"
  export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUNNING_AS_ID}/bus"
  : "${DISPLAY:=0}"
  export DISPLAY
  export HOME="/home/${RUNNING_AS}"


  local device_id
  device_id="$(__get_device_id)"

  local natscroll_enabled
  natscroll_enabled="$(
    __get_prop_id "${device_id}" 'Natural Scrolling Enabled'
  )"

  local scrollmeth_enabled
  scrollmeth_enabled="$(
    __get_prop_id "${device_id}" 'Scroll Method Enabled'
  )"

  local scrollbutton
  scrollbutton="$(
    __get_prop_id "${device_id}" 'Button Scrolling Button'
  )"

  __run_xinput_as set-prop "${device_id}" "${natscroll_enabled}" 1
  __run_xinput_as set-prop "${device_id}" "${scrollmeth_enabled}" 0 0 1
  __run_xinput_as set-prop "${device_id}" "${scrollbutton}" 8
}

__get_device_id() {
  __run_xinput_as list |
    awk '/Logitech USB Trackball/ { sub(/id=/, "", $6); print $6 }'
}

__get_prop_id() {
  local device_id="${1}"
  local propmatch="${2}"
  __run_xinput_as list-props "${device_id}" |
    awk -F: '/'"${propmatch}"' \([0-9]+\)/ {
      sub(/.+\(/, "", $1);
      sub(/\).*/, "", $1);
      print $1;
    }'
}

__run_xinput_as() {
  sudo -E -u "${RUNNING_AS}" "${XINPUT_EXE}" "${@}"
}

main "${@}"
