#!/usr/bin/bash
# Toggle InputPlumber between gamepad mode and joystick→mouse mode.
# Both halves of the toggle need to set TWO things:
#   1. ProfilePath  — what events the source produces
#   2. TargetDevices — which virtual devices receive events
# (LoadProfilePath alone doesn't change targets; SetTargetDevices
#  alone keeps the previous mappings.)
set -eu
DEV=/org/shadowblip/InputPlumber/CompositeDevice0
SVC=org.shadowblip.InputPlumber
IFACE=org.shadowblip.Input.CompositeDevice

# pocketds-gamepad.yaml mirrors upstream default.yaml but ALSO
# emits dbus: ui_guide on Guide so the mode-listener can flip
# back into joymouse via the AYANEO logo button.
GAMEPAD=/usr/share/inputplumber/profiles/pocketds-gamepad.yaml
JOYMOUSE=/usr/share/inputplumber/profiles/pocketds-joymouse.yaml

cur=$(busctl get-property "$SVC" "$DEV" "$IFACE" ProfilePath 2>/dev/null \
      | sed -E 's/^s "(.*)"$/\1/')

# Inverted-default: anything that isn't pocketds-gamepad.yaml lands
# in the "*)" branch and gets sent to gamepad mode. That branch
# covers two cases:
#   1. Joymouse → Gamepad  (the user-facing toggle direction)
#   2. default.yaml → Gamepad  (the bootstrap path at boot, where
#      InputPlumber starts on its built-in default profile and
#      pocketds-mode-listener kicks it into gamepad on startup so
#      the Guide button is actually wired to dbus: ui_guide)
case "$cur" in
    "$GAMEPAD")
        # → joymouse. dbus stays in the target list so the Guide
        # button toggles back to gamepad mode.
        busctl call "$SVC" "$DEV" "$IFACE" SetTargetDevices as 3 mouse keyboard dbus
        busctl call "$SVC" "$DEV" "$IFACE" LoadProfilePath s "$JOYMOUSE"
        notify-send -u low "Pocket DS" "Joystick → mouse + keyboard" 2>/dev/null || true
        ;;
    *)
        # → gamepad. xbox-elite gives us four paddle slots so the
        # MCU's BTN_3/BTN_4 cap-map entries (Right/LeftPaddle2)
        # have somewhere to land on the virtual gamepad target.
        busctl call "$SVC" "$DEV" "$IFACE" SetTargetDevices as 2 xbox-elite dbus
        busctl call "$SVC" "$DEV" "$IFACE" LoadProfilePath s "$GAMEPAD"
        notify-send -u low "Pocket DS" "Gamepad mode" 2>/dev/null || true
        ;;
esac
