#!/bin/bash

# omarchy:summary=Print PulseAudio sink or source availability for the shell
# omarchy:group=audio
# omarchy:args=[sources]

# With "sources", print source availability instead: a jack input such as a
# headset microphone reports its port unavailable while nothing is plugged in.
# pactl translates the listing ("not available" too), so it is read in the C
# locale.
kind=sinks
header="Sink #"
if [[ ${1:-} == "sources" ]]; then
  kind=sources
  header="Source #"
fi

# A speaker tuning is a virtual sink in front of the real speakers. Both exist
# in the graph, but selecting the physical one would only bypass the tuning, so
# report it unavailable and keep it out of the output list.
fronted=""
[[ $kind == sinks ]] && fronted="$(omarchy-audio-tuning fronted-sink 2>/dev/null || true)"

LC_ALL=C pactl list "$kind" 2>/dev/null | awk -v fronted="$fronted" -v header="$header" '
  function emit_sink() {
    if (name == "") return
    if (fronted != "" && name == fronted) {
      print name "\t0"
      return
    }
    print name "\t" ((port_count == 0 || available) ? 1 : 0)
  }

  index($0, header) == 1 {
    emit_sink()
    name = ""
    in_ports = 0
    port_count = 0
    available = 0
    next
  }

  /^[[:space:]]*Name:/ {
    name = $2
    next
  }

  /^[[:space:]]*Ports:$/ {
    in_ports = 1
    next
  }

  in_ports && /^\tActive Port:/ {
    in_ports = 0
    next
  }

  in_ports && /^\t\t/ {
    port_count++
    if ($0 !~ /not available/) available = 1
    next
  }

  END {
    emit_sink()
  }
'
