#!/bin/bash
# udt-keyboard: light the Ajazz AK820 Pro in the wallpaper accent.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
#
# Usage: udt-keyboard           set the keyboard to the current accent
#        udt-keyboard --watch   do that again every time it is plugged in
#
# The colour is the one udt-accent wrote for rofi, so the keyboard follows the
# wallpaper like the window borders do. udt-accent starts this detached on
# every run; the watcher is started from hypr-theme's autostart, because the
# keyboard only takes commands over the USB cable and may be plugged in long
# after the last wallpaper change.
#
# Talks to the keyboard through ak820-ctl, which the udev rule shipped with it
# lets the logged-in user drive without root. Without ak820-ctl, or with the
# keyboard on the 2.4G dongle or Bluetooth, this does nothing.

command -v ak820-ctl >/dev/null || exit 0

# "launch": dark until a key is pressed, which lights outward along its row.
MODE=launch

apply() {
    local accent
    accent="$(grep -o 'accent: #[0-9a-fA-F]\{6\}' "$HOME/.cache/udt/udt-accent.rasi" 2>/dev/null)"
    [ -n "$accent" ] || return 0

    # A wallpaper change and a plug-in can land together, and two interleaved
    # off/mode pairs leave the keyboard on whichever off came last.
    exec 9>"${XDG_RUNTIME_DIR:-/tmp}/udt-keyboard.lock"
    flock 9

    # This firmware ignores a mode change unless the lights were turned off
    # first and given time to settle; one second was not enough, three is.
    ak820-ctl light off >/dev/null 2>&1 || return 0
    sleep 3
    ak820-ctl light "$MODE" -c "${accent#accent: #}" >/dev/null 2>&1
}

if [ "$1" != --watch ]; then
    apply
    exit
fi

# One usb_device event per plug-in; its interfaces and hidraw nodes would each
# fire again. udevadm prints an event once its rules have run, so the uaccess
# ACL is already in place, but the keyboard needs a moment to boot.
/sbin/udevadm monitor --udev --subsystem-match=usb/usb_device --property |
while read -r line; do
    case "$line" in
        ACTION=*) action="${line#ACTION=}" ;;
        PRODUCT=c45/8009/*) [ "$action" = add ] && { sleep 2; apply; } & ;;
    esac
done
