#!/bin/bash

# omarchy:summary=Install support for using Xbox controllers with Steam/RetroArch/etc.
# omarchy:group=install
# omarchy:name=gaming xbox-controllers
# omarchy:requires-sudo=true

set -e

echo "Installing Xbox controller Bluetooth support..."

# linux-omarchy ships xpadneo prebuilt and signed, the only kind Secure Boot loads; other kernels, or a prebuilt one behind the kernel, use DKMS.
# Kernels are the packages owning a modules.builtin, which the tree kernel-modules-hook keeps for the running one is not.
kernels=$(pacman -Qqo /usr/lib/modules/*/modules.builtin 2>/dev/null | sort -u || true)
kernel=$(pacman -Q linux-omarchy 2>/dev/null | cut -d' ' -f2)
offered=$(pacman -Si linux-omarchy-xpadneo 2>/dev/null | grep -o -m1 'linux-omarchy=[^ ]*' || true)
# A kernel pinned with IgnorePkg would leave the module package unable to update; case matches as pacman's fnmatch does.
pinned=false
while read -r pattern; do
  case linux-omarchy in $pattern) pinned=true ;; esac
done < <(LC_ALL=C pacman-conf IgnorePkg 2>/dev/null || true)

if omarchy-pkg-present linux-omarchy-xpadneo xpadneo; then
  : # Already set up prebuilt, which a pin added since then does not undo.
elif [[ $kernels == "linux-omarchy" && -n $kernel && $offered == "linux-omarchy=$kernel" ]] && ! $pinned && pacman -Si xpadneo &>/dev/null; then
  # Both packages conflict with xpadneo-dkms, so --ask 4 swaps out a DKMS install in one transaction.
  sudo pacman -S --noconfirm --needed --ask 4 linux-omarchy-xpadneo xpadneo
else
  omarchy-pkg-add xpadneo-dkms
fi

# Load xpadneo for Bluetooth controllers while keeping xpad available for USB controllers
echo hid_xpadneo | sudo tee /etc/modules-load.d/xpadneo.conf >/dev/null

# BLE controllers discard a pairing that doesn't include the host's identity key
omarchy-apply-bluetooth-privacy

# Controllers need no input group: uaccess gives the active seat's user the joystick
# nodes, while input would let any process they run read and inject keystrokes.

# After a kernel update without a reboot, the module exists only for the kernel that has not booted yet.
if ! sudo modprobe hid_xpadneo; then
  if omarchy-pkg-present xpadneo-dkms && grep -qs -e '\[integrity\]' -e '\[confidentiality\]' /sys/kernel/security/lockdown; then
    echo "Secure Boot refuses the driver DKMS built. Xbox controllers load under Secure Boot when linux-omarchy is the only kernel."
  else
    echo "Reboot to load the Xbox controller driver."
  fi
fi

echo ""
echo "Now you can pair your Xbox controller with Bluetooth using Super + Ctrl + B."
