#!/bin/bash
set -e

# TODO: multiple fast invocation cause volume not to be updated

PACTL_SINK='@DEFAULT_SINK@'
SINK="$PACTL_SINK"

function get_vol() {
    VOL="$(pactl get-sink-volume "$SINK" 2> /dev/null)"

    if [ -n "$VOL" ]; then
        CMD='pactl set-sink-volume'
    else
        CMD='amixer sset'
        SINK='Master'

        VOL="$(amixer sget "$SINK")"
    fi
}

set +e
get_vol
set -e

VOL="$(echo "$VOL" | grep -Po '\d+(?=%)' | head -n 1)"
VOL="$((VOL - VOL % "$1"))"

case "${1:0:1}" in
    '')
        exit 1
        ;;
    '+'|'-')
        VOL="$((VOL + "$1"))"
        ;;
    *)
        VOL="$1"
        ;;
esac

[ "$VOL" -lt 0 ] && VOL=0
[ "$VOL" -gt 100 ] && VOL=100

$CMD "$SINK" "$VOL%" > /dev/null
pactl set-sink-mute "$PACTL_SINK" 0

echo "$VOL"
