#!/usr/bin/env bash
# Audio output devices via wireplumber (wpctl).
#   sinks            JSON list of output devices  [{id,name,default}]
#   set-default <id> make <id> the default sink (and move running streams)
set -u

case "${1:-sinks}" in
  sinks)
    wpctl status | awk '
      /^Audio/{sec="audio"} /^Video/{sec="video"}
      /Sinks:/{insink=(sec=="audio")?1:0; next}
      /Sources:|Filters:|Streams:/{insink=0}
      insink && match($0,/[0-9]+\./){
        def=($0 ~ /\*/)?"true":"false"
        id=substr($0,RSTART,RLENGTH-1)
        name=substr($0,RSTART+RLENGTH)
        sub(/ *\[vol:.*$/,"",name)
        gsub(/^[ \t]+|[ \t]+$/,"",name)
        printf "%s\t%s\t%s\n",id,def,name
      }' \
    | jq -R -s -c 'split("\n")|map(select(length>0))|map(split("\t"))
                   |map({id:.[0],default:(.[1]=="true"),name:.[2]})'
    ;;
  set-default)
    id="${2:-}"
    [ -n "$id" ] || exit 1
    wpctl set-default "$id"
    # move already-playing streams onto the new default too
    def=$(pactl get-default-sink 2>/dev/null)
    if [ -n "$def" ]; then
      pactl list short sink-inputs 2>/dev/null | awk '{print $1}' | while read -r si; do
        pactl move-sink-input "$si" "$def" 2>/dev/null
      done
    fi
    ;;
esac
