#!/usr/bin/env bash
set -euo pipefail

devices=$(hyprctl devices -j)

# Tag each device with its type so the right block can be emitted on selection.
entries=$(jq -r '
    (.keyboards[]?.name | "keyboard\t" + .),
    (.mice[]?.name     | "mouse\t"    + .)
' <<<"$devices")

if [[ -z "$entries" ]]; then
    echo "No keyboard or mouse devices found" >&2
    exit 1
fi

if command -v fzf &>/dev/null; then
    selected=$(printf '%s\n' "$entries" | fzf --prompt="Select device: " --height=~10 --with-nth=2.. --delimiter='\t')
else
    echo "Select a device:" >&2
    IFS=$'\n'
    select selected in $entries; do
        [[ -n "$selected" ]] && break
    done
    unset IFS
fi

[[ -z "$selected" ]] && exit 1

type=${selected%%$'\t'*}
name=${selected#*$'\t'}

case "$type" in
keyboard)
    cat <<EOF
hl.device({
    name = "$name",
    kb_layout  = "",
    kb_variant = "",
    kb_model   = "",
    kb_options = "",
    kb_rules   = "",
    repeat_rate  = 0,
    repeat_delay = 0,
    sensitivity  = 0,
})
EOF
    ;;
mouse)
    cat <<EOF
hl.device({
    name = "$name",
    sensitivity   = 0,
    accel_profile = "",
    left_handed   = false,
    natural_scroll = false,
    scroll_points = "",
})
EOF
    ;;
esac
