#!/bin/bash

# omarchy:summary=Adjust output volume and show the Omarchy OSD
# omarchy:args=<raise|lower|mute-toggle|+N|-N>
# omarchy:examples=omarchy audio output volume raise | omarchy audio output volume lower | omarchy audio output volume mute-toggle | omarchy audio output volume +1

action="${1:-}"

if [[ -z $action ]]; then
  echo "Usage: omarchy-audio-output-volume <raise|lower|mute-toggle|+N|-N>"
  exit 1
fi

# Resolve through any DSP sink to the physical one, so the keys always move real
# loudness and the processing always sees full-scale input. Shared with the audio
# panel and the output switcher.
sink="$(omarchy-audio-output-sink)"
if [[ -z $sink ]]; then
  echo "Could not resolve an audio sink to control." >&2
  exit 1
fi

# pactl translates its labels and yes/no; parse them in the C locale.
read_volume() {
  local line channel raw
  local -a channels
  line=$(LC_ALL=C pactl get-sink-volume "$sink" 2>/dev/null) || return
  line=${line%%$'\n'*}
  IFS=, read -r -a channels <<<"${line#Volume:}"

  channel_volumes=()
  peak=-1
  for channel in "${channels[@]}"; do
    [[ $channel =~ ^[[:space:]]*[^:]+:[[:space:]]+([0-9]+)[[:space:]]+/[[:space:]]+([0-9]+)% ]] || return 1
    raw=${BASH_REMATCH[1]}
    channel_volumes+=("$raw")
    if ((raw > peak)); then
      peak=$raw
      percent=${BASH_REMATCH[2]}
    fi
  done
  ((peak >= 0))
}

volume_muted() {
  [[ $(LC_ALL=C pactl get-sink-mute "$sink" 2>/dev/null) == *yes ]]
}

case "$action" in
  raise) action="+5" ;;
  lower) action="-5" ;;
esac

if [[ $action == "mute-toggle" ]]; then
  runtime_dir="${XDG_RUNTIME_DIR:-/tmp}"
  debounce_file="$runtime_dir/omarchy-audio-output-volume-mute-toggle.last"
  now_us=${EPOCHREALTIME//[!0-9]/}
  now=$(( 10#$now_us / 1000 ))
  last=0
  [[ -r $debounce_file ]] && read -r last <"$debounce_file" || true
  if ((now - last < 250)); then
    exit 0
  fi
  printf '%s\n' "$now" >"$debounce_file"

  pactl set-sink-mute "$sink" toggle
  read_volume || percent=0
  if volume_muted || ((${percent:-0} == 0)); then
    icon="volume-muted"
  else
    icon="volume-high"
  fi
elif [[ $action =~ ^([+-])([0-9]+)$ ]]; then
  direction="${BASH_REMATCH[1]}"
  step="${BASH_REMATCH[2]}"

  if ! read_volume; then
    echo "Could not read volume for $sink." >&2
    exit 1
  fi

  if [[ $direction == "+" ]]; then
    next=$((percent + step))
    ((next <= 100)) || next=100
  else
    next=$((percent - step))
    ((next >= 0)) || next=0
  fi

  if ((peak == 0 || ${#channel_volumes[@]} > 31)); then
    # A silent sink has no channel ratio to scale, and pactl takes at most 31 separate values.
    volumes=("${next}%")
  else
    # pactl accepts one raw volume per channel in channel-map order.
    target=$((next * 65536 / 100)) # PA_VOLUME_NORM is 65536.
    volumes=()
    for raw in "${channel_volumes[@]}"; do
      volumes+=("$(((raw * target + peak / 2) / peak))")
    done
  fi

  pactl set-sink-volume "$sink" "${volumes[@]}" || exit 1
  pactl set-sink-mute "$sink" 0 || exit 1
  percent=$next
  if ((percent == 0)); then
    icon="volume-muted"
  else
    icon="volume-high"
  fi
else
  echo "Unknown volume action: $action"
  exit 1
fi

omarchy-osd -i "$icon" -p "${percent:-0}"
