#!/bin/bash

# Copyright (c) 2020 Guillaume Deflaux, Marco Buzzanca
#
# Based on the work of:
#   2014 Julien Bonjean <julien@bonjean.info>
#   2014 Alexander Keller <github@nycroth.com>
#
# GNU GENERAL PUBLIC LICENSE
#    Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Optional step, unit and ALSA mixer arguments retain their existing meaning.
STEP="${1:-$(xrescat i3xrocks.volume.step 5)}"
UNIT="${2:-$(xrescat i3xrocks.volume.unit %)}"
MIXER="${3:-$(xrescat i3xrocks.volume.mixer '')}"
SCONTROL="${BLOCK_INSTANCE:-}"
EXPLICIT_ALSA=false
if [ -n "$MIXER" ] || [ -n "$SCONTROL" ]; then
    EXPLICIT_ALSA=true
fi
if [ -z "$MIXER" ]; then
    MIXER=default
    if lsmod 2>/dev/null | grep -q jack; then
        MIXER=jackplug
    fi
fi
STEP="${STEP%"$UNIT"}"
export LC_ALL=C

# All readers publish both fields only after checking the command and output.
# wpctl exposes a linear volume, but no native dB reading.
read_pipewire() {
    [ "$UNIT" = '%' ] || return 1
    local output
    output=$(wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null) || return 1
    if [[ "$output" =~ ^Volume:[[:space:]]+([0-9]+([.][0-9]+)?)([[:space:]]+\[MUTED\])?[[:space:]]*$ ]]; then
        VALUE=$(awk -v volume="${BASH_REMATCH[1]}" 'BEGIN {printf "%.0f", volume * 100}')
        STATUS=on
        [[ "$output" == *'[MUTED]'* ]] && STATUS=off
        return 0
    fi
    return 1
}

read_pulse() {
    local output mute
    output=$(pactl get-sink-volume @DEFAULT_SINK@ 2>/dev/null) || return 1
    mute=$(pactl get-sink-mute @DEFAULT_SINK@ 2>/dev/null) || return 1
    case "$mute" in
        'Mute: yes') STATUS=off ;;
        'Mute: no') STATUS=on ;;
        *) return 1 ;;
    esac
    case "$UNIT" in
        '%')
            [[ "$output" =~ /[[:space:]]*([0-9]+)%[[:space:]]*/ ]] || return 1
            VALUE="${BASH_REMATCH[1]}"
            ;;
        dB)
            [[ "$output" =~ /[[:space:]]*([+-]?[0-9]+([.][0-9]+)?|-inf)[[:space:]]+dB ]] || return 1
            VALUE="${BASH_REMATCH[1]}"
            ;;
        *) return 1 ;;
    esac
}

prepare_alsa() {
    if [ -z "$SCONTROL" ]; then
        local controls
        controls=$(amixer -D "$MIXER" scontrols 2>/dev/null) || return 1
        SCONTROL=$(sed -n "s/Simple mixer control '\(.*\)',0/\1/p" <<< "$controls" | head -n1)
    fi
    [ -n "$SCONTROL" ]
}

read_alsa() {
    local output
    prepare_alsa || return 1
    output=$(amixer -D "$MIXER" get "$SCONTROL" 2>/dev/null) || return 1
    CAPABILITY=()
    if [[ "$output" == *'cvolume'* ]]; then
        CAPABILITY=(Capture)
        output=$(amixer -D "$MIXER" get "$SCONTROL" Capture 2>/dev/null) || return 1
    fi
    [[ "$output" =~ \[(on|off)\] ]] || return 1
    STATUS="${BASH_REMATCH[1]}"
    case "$UNIT" in
        '%')
            [[ "$output" =~ \[([0-9]+)%\] ]] || return 1
            VALUE="${BASH_REMATCH[1]}"
            ;;
        dB)
            [[ "$output" =~ \[([+-]?[0-9]+([.][0-9]+)?|-inf)dB\] ]] || return 1
            VALUE="${BASH_REMATCH[1]}"
            ;;
        *) return 1 ;;
    esac
}

select_backend() {
    BACKEND=''
    if ! "$EXPLICIT_ALSA"; then
        if command -v wpctl >/dev/null && read_pipewire; then
            BACKEND=pipewire
            return 0
        fi
        if command -v pactl >/dev/null && read_pulse; then
            BACKEND=pulse
            return 0
        fi
    fi
    if command -v amixer >/dev/null && read_alsa; then
        BACKEND=alsa
        return 0
    fi
    VALUE=''
    STATUS=off
    return 1
}

# Choose a usable backend before dispatching a button. Never replay a button
# when refreshing state, even if the server disappears after the mutation.
select_backend || true

toggle() {
    case "$BACKEND" in
        pipewire) wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle ;;
        pulse) pactl set-sink-mute @DEFAULT_SINK@ toggle ;;
        alsa) amixer -q -D "$MIXER" sset "$SCONTROL" "${CAPABILITY[@]}" toggle ;;
    esac
}

# Raising the volume stops at 100% (0 dB), as with the volume keys and in the
# sway session. ALSA mixers stop at their maximum by themselves.
over_limit() {
    local limit=100
    [ "$UNIT" = dB ] && limit=0
    [ "$VALUE" != -inf ] && awk -v value="$VALUE" -v step="$STEP" -v limit="$limit" \
        'BEGIN { exit !(value + step > limit) }'
}

adjust_volume() {
    local direction="$1"
    case "$BACKEND" in
        pipewire)
            if [ "$direction" = + ]; then
                wpctl set-volume -l 1.0 @DEFAULT_AUDIO_SINK@ "${STEP}%+"
            else
                wpctl set-volume @DEFAULT_AUDIO_SINK@ "${STEP}%-"
            fi
            ;;
        pulse)
            if [ "$direction" = + ] && over_limit; then
                if [ "$UNIT" = dB ]; then
                    pactl set-sink-volume @DEFAULT_SINK@ 0dB
                else
                    pactl set-sink-volume @DEFAULT_SINK@ 100%
                fi
            else
                pactl set-sink-volume @DEFAULT_SINK@ "${direction}${STEP}${UNIT}"
            fi
            ;;
        alsa) amixer -q -D "$MIXER" sset "$SCONTROL" "${CAPABILITY[@]}" "${STEP}${UNIT}${direction}" ;;
    esac
}

volume_up() { adjust_volume +; }
volume_down() { adjust_volume -; }

ACTION_1=$(xrescat i3xrocks.action.volume.left "true")
ACTION_2=$(xrescat i3xrocks.action.volume.middle "true")
ACTION_3=$(xrescat i3xrocks.action.volume.right "toggle")
ACTION_4=$(xrescat i3xrocks.action.volume.scrollup "volume_up")
ACTION_5=$(xrescat i3xrocks.action.volume.scrolldn "volume_down")
case "${BLOCK_BUTTON:-}" in
    1) eval "$ACTION_1" ;;
    2) eval "$ACTION_2" ;;
    3) eval "$ACTION_3" ;;
    4) eval "$ACTION_4" ;;
    5) eval "$ACTION_5" ;;
esac
# Default and configured actions share the same refresh path.
select_backend || true

if [ -n "$VALUE" ]; then
    if [ "$UNIT" = '%' ]; then
        VALUE=$(printf '%02d%%' "$((10#$VALUE))")
    else
        VALUE="${VALUE}dB"
    fi
else
    VALUE='   '
fi

LABEL_COLOR=${label_color:-$(xrescat i3xrocks.label.color "#E6E1CF")}
if [ "$STATUS" = on ]; then
    ICON=${icon_on:-$(xrescat i3xrocks.label.sound S)}
    VALUE_COLOR=${color:-$(xrescat i3xrocks.value.color "#E6E1CF")}
else
    ICON=${icon_mute:-$(xrescat i3xrocks.label.mute M)}
    VALUE_COLOR=${warn_color:-$(xrescat i3xrocks.warning "#FFD580")}
fi
VALUE_FONT=${font:-$(xrescat i3xrocks.value.font "Source Code Pro Medium 13")}
printf '<span font_desc="%s" color="%s">%s</span><span font_desc="%s" color="%s"> %s</span>\n' \
    "$VALUE_FONT" "$LABEL_COLOR" "$ICON" "$VALUE_FONT" "$VALUE_COLOR" "$VALUE"
