#!/bin/bash

# omarchy:summary=Set the default audio output and move active streams
# omarchy:args=<node-id> <sink-name>
# omarchy:examples=omarchy audio output set default 42 alsa_output.pci-0000_00_1f.3.analog-stereo

node_id=${1:-}
sink_name=${2:-}

if [[ -z $node_id || -z $sink_name ]]; then
  echo "Usage: omarchy-audio-output-set-default <node-id> <sink-name>" >&2
  exit 1
fi

timeout 2 wpctl set-default "$node_id" 2>/dev/null || true
timeout 2 pactl set-default-sink "$sink_name" 2>/dev/null || true

# Move only real application streams. A DSP filter-chain's own output is also a
# sink input but carries no application.name, and moving it would rewire the
# processing itself -- onto headphones, or into its own virtual sink, which is a
# cycle. EasyEffects' output stream must stay put for the same reason.
timeout 2 pactl list sink-inputs 2>/dev/null | awk '
  /^Sink Input #/ {id = substr($3, 2)}
  /application\.name = / {
    app = $0
    sub(/.*application\.name = "/, "", app)
    sub(/"$/, "", app)
    if (app != "EasyEffects") print id
  }' | while read -r input; do
  [[ -n $input ]] && timeout 2 pactl move-sink-input "$input" "$sink_name" 2>/dev/null || true
done
