#!/bin/bash
KBD_ID=$(xinput list | grep -i "G910" | grep -oP 'id=\K[0-9]+')
echo "G910 at id=$KBD_ID"
echo "Alt+F1 toggles turbo | Escape = panic stop"

# Keycodes: Space=65, Alt=64, F1=67, Escape=9
TURBO_ENABLED=true
TURBO_PID=""
ALT_HELD=false

enable_turbo() {
    TURBO_ENABLED=true
    xset -r 65       # suppress fake repeats while turbo is active
    echo "[Turbo] ENABLED — hold Space to rapid-fire"
}

disable_turbo() {
    TURBO_ENABLED=false
    [ -n "$TURBO_PID" ] && kill "$TURBO_PID" 2>/dev/null
    pkill -f 'xdotool key space' 2>/dev/null   # kill any orphans
    TURBO_PID=""
    xset r 65        # restore normal spacebar repeat
    echo "[Turbo] DISABLED — Space works normally"
}

cleanup() {
    disable_turbo
    echo "[Turbo] Exiting cleanly."
    exit 0
}

trap cleanup SIGINT SIGTERM

# Boot with turbo on by default — change to disable_turbo to boot OFF
enable_turbo

# Process substitution keeps variables in current shell (not a subshell)
while read -r line; do

    # Track Alt held state
    if echo "$line" | grep -q "key press *64$"; then
        ALT_HELD=true
    elif echo "$line" | grep -q "key release *64$"; then
        ALT_HELD=false

    # Alt+F1 → toggle
    elif echo "$line" | grep -q "key press *67$"; then
        if [ "$ALT_HELD" = true ]; then
            if [ "$TURBO_ENABLED" = true ]; then
                disable_turbo
            else
                enable_turbo
            fi
        fi

    # Space press → start turbo (only if enabled)
    elif echo "$line" | grep -q "key press *65$"; then
        if [ "$TURBO_ENABLED" = true ]; then
            ( while true; do xdotool key space; sleep 0.04; done ) &
            TURBO_PID=$!
        fi

    # Space release → stop turbo
    elif echo "$line" | grep -q "key release *65$"; then
        [ -n "$TURBO_PID" ] && kill "$TURBO_PID" 2>/dev/null
        TURBO_PID=""

    # Escape → panic stop
    elif echo "$line" | grep -q "key press *9$"; then
        cleanup
    fi

done < <(xinput test "$KBD_ID")

