#!/bin/bash

# pavolctl
#
# Provides an easy method of setting the default sink volume in PulseAudio and
# allows toggling mute on the sink.

PULSEAUDIO_SINK="${PULSEAUDIO_SINK:-"@DEFAULT_SINK@"}"
VOLUME_LIMIT="${VOLUME_LIMIT:-150}"

TARGET="$1"
ADJUSTMENT="$2"

echo "${TARGET:?} ${ADJUSTMENT:?}" >/dev/null

function limit_level() {
    level="$(pactl get-sink-volume "$PULSEAUDIO_SINK" | grep '^Volume' | cut -d' ' -f5 | grep -o "[[:digit:]]*")"

    if [[ "$level" -gt "$VOLUME_LIMIT" ]]; then
        echo "Limiting volume to: $1"
        set_level $VOLUME_LIMIT%
    fi
}

function set_level() {
    echo "Desired volume adjustment: $1"
    pactl set-sink-volume "$PULSEAUDIO_SINK" "$1"
}

if [[ "$TARGET" == "volume" ]]; then
    set_level "$ADJUSTMENT"
    limit_level "$VOLUME_LIMIT"
elif [[ "$TARGET" == "toggle" ]]; then
    amixer -D pulse sset "$ADJUSTMENT" toggle
else
    echo "Invalid option: $TARGET $ADJUSTMENT"
    exit 1
fi

killall -SIGUSR1 i3status
