#! /bin/bash

FF_STREAM=$(wpctl status | grep "Firefox *$" | awk -F. '{ print $1 }')
MUSIC_STREAM=$(wpctl status | grep "Chromium *$" | awk -F. '{ print $1 }')
SPEAKER_SINK=$(wpctl status | grep "Family 17h/19h HD Audio Controller Speaker + Headphones \[" | awk -F'[. ]' '{ print $7 }')

function setvol {
    VOL=$(echo "scale=2;$2/100" | bc -l)
    wpctl set-volume $1 "$VOL"
}

aseqdump -p 28 | \
while IFS=" ," read src ev1 ev2 ch label1 data1 label2 data2; do
    case "$data1" in
        # slider music
        "3")
            setvol $MUSIC_STREAM $data2
            ;;
        # slider firefox
        "7")
            setvol $FF_STREAM $data2
            ;;
        # Knob speakers
        "16")
            setvol $SPEAKER_SINK $data2
            ;;
        # Play and Stop buttons
        "41"|"42")
            xdotool key XF86AudioPlay
            ;;
        # Previous song
        "43")
            if [ $data2 -eq 127 ]; then xdotool key XF86AudioPrev; fi
            ;;
        # Next song
        "44")
            if [ $data2 -eq 127 ]; then xdotool key XF86AudioNext; fi
            ;;
        # Restart script
        "46")
            if [ $data2 -eq 127 ]; then systemctl --user restart midi.service; fi
            ;;
        # Mute music
        "51")
            ;;
    esac
done