#!/bin/bash

# omarchy:summary=Switch between audio outputs while preserving the mute status

# Skip the physical sink an active speaker tuning fronts: rotating onto it would
# silently bypass the tuning rather than pick a different output.
fronted=$(omarchy-audio-tuning fronted-sink 2>/dev/null || true)

# pactl translates availability, headers and yes/no; parse them in the C locale.
current_sink_name=$(timeout 2 pactl get-default-sink)

next_sink_index=""
next_sink_name=""
next_sink_description=""
next_sink_json_volume=""

{
  IFS= read -r -d '' next_sink_index &&
    IFS= read -r -d '' next_sink_name &&
    IFS= read -r -d '' next_sink_description &&
    IFS= read -r -d '' next_sink_json_volume
} < <(LC_ALL=C timeout 2 pactl -f json list sinks |
  jq -j --arg fronted "$fronted" --arg current "$current_sink_name" '
    [.[]
      | select((.ports | length == 0) or ([.ports[]? | .availability != "not available"] | any))
      | select($fronted == "" or .name != $fronted)] as $sinks
    | if ($sinks | length) == 0 then empty else
        (($sinks | map(.name) | index($current)) as $idx
          | if $idx != null then ($idx + 1) % ($sinks | length) else 0 end) as $next_idx
        | $sinks[$next_idx]
        | [
            (.index | tostring),
            .name,
            ((.description // .properties."device.description" // .name) | gsub("[\t\r\n]"; " ")),
            ((.volume | to_entries[0]?.value.value_percent // "") | sub("%$"; ""))
          ]
        | map(. + "\u0000") | add
      end
  ')

if [[ -z $next_sink_name ]]; then
  omarchy-osd -m "$(omarchy-i18n audio.noDevices)"
  exit 1
fi

# A tuning sink sits at a fixed 100% and unmuted while real loudness lives on the
# physical sink beneath it, so read the level from whichever sink actually carries
# it or the OSD contradicts the volume keys.
next_sink_effective=$(omarchy-audio-output-sink "$next_sink_name")
vol_line=$(LC_ALL=C timeout 2 pactl get-sink-volume "$next_sink_effective" 2>/dev/null)
vol_line=${vol_line%%$'\n'*}
if [[ $vol_line =~ ([0-9]+)% ]]; then
  next_sink_volume=${BASH_REMATCH[1]}
else
  next_sink_volume=${next_sink_json_volume:-0}
fi
if [[ $(LC_ALL=C timeout 2 pactl get-sink-mute "$next_sink_effective" 2>/dev/null) == *yes ]]; then
  next_sink_is_muted=true
else
  next_sink_is_muted=false
fi

if [[ $next_sink_is_muted == "true" ]] || (( next_sink_volume == 0 )); then
  icon_state="muted"
elif (( next_sink_volume <= 33 )); then
  icon_state="low"
elif (( next_sink_volume <= 66 )); then
  icon_state="medium"
else
  icon_state="high"
fi

if [[ $next_sink_name != "$current_sink_name" ]]; then
  omarchy-audio-output-set-default "$next_sink_index" "$next_sink_name"
fi

omarchy-osd -i "volume-${icon_state}" -m "$next_sink_description"
