#!/usr/bin/bash

mute(){
    wpctl set-mute "$1" toggle
}

change(){
    wpctl set-volume "$1" "$2"%
}

get-volume(){
    volume="$(\
        wpctl get-volume "$1" |
        cut -d' ' -f2 |\
        sed 's/\.//; s/^0*//')"

    grep "MUTED" <<< $(wpctl get-volume "$1") &> /dev/null \
        && muted="true" \
        || muted="false"

    jq --null-input --compact-output \
        --arg volume "$volume" \
        --arg muted "$muted" \
        '$ARGS.named'
}

cmd="$1"; shift
dev="$1"; shift

case "$dev" in
    output ) dev="@DEFAULT_AUDIO_SINK@"   ;;
    input  ) dev="@DEFAULT_AUDIO_SOURCE@" ;;
esac

case "$cmd" in
    mute   ) mute "$dev" "$@"   ;;
    change ) change "$dev" "$@" ;;
    get    ) 
        jq --null-input --compact-output \
            --argjson output "$(get-volume "@DEFAULT_AUDIO_SINK@")" \
            --argjson input "$(get-volume "@DEFAULT_AUDIO_SOURCE@")" \
            '$ARGS.named'
        ;;
esac

