#!/usr/bin/env bash
set -euo pipefail

notify() {
    notify-send "󰕾 Audio" "$1"
}

require_wpctl() {
    if ! command -v wpctl >/dev/null 2>&1; then
        notify "wpctl ist nicht installiert."
        exit 1
    fi
}

choose_sink() {
    wpctl status |
        awk '
            /Sinks:/ {in_sinks=1; next}
            /Sources:/ {in_sinks=0}
            in_sinks && /\*/ {gsub(/^[[:space:]]*[│├└─* ]*/, ""); print "󰓃  " $0}
            in_sinks && /^[[:space:]]*[│├└─ ]*[0-9]+\./ {gsub(/^[[:space:]]*[│├└─ ]*/, ""); print "󰓃  " $0}
        ' |
        wofi --dmenu --prompt "󰕾  Audioausgabe" --insensitive
}

require_wpctl

choice="$(
    printf '%s\n' \
        "󰝝  Lauter" \
        "󰝞  Leiser" \
        "󰖁  Stumm schalten" \
        "󰓃  Ausgabe wechseln" \
        "󰍬  Mikrofon stumm" \
        "󰎆  Play/Pause" \
        "󰒮  Naechster Titel" \
        "󰒭  Vorheriger Titel" \
        "󰩟  Status" |
        wofi --dmenu --prompt "󰕾  Audio" --insensitive
)"

case "$choice" in
    *"Lauter"*)
        wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 5%+
        ;;
    *"Leiser"*)
        wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-
        ;;
    *"Stumm schalten"*)
        wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle
        ;;
    *"Ausgabe wechseln"*)
        selection="$(choose_sink)"
        [ -n "$selection" ] || exit 0
        sink_id="$(printf '%s\n' "$selection" | sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p')"
        [ -n "$sink_id" ] || exit 0
        wpctl set-default "$sink_id" && notify "Audioausgabe gewechselt."
        ;;
    *"Mikrofon stumm"*)
        wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle
        ;;
    *"Play/Pause"*)
        playerctl play-pause
        ;;
    *"Naechster Titel"*)
        playerctl next
        ;;
    *"Vorheriger Titel"*)
        playerctl previous
        ;;
    *"Status"*)
        wpctl status | wofi --dmenu --prompt "󰩟  Audiostatus"
        ;;
esac
