#!/usr/bin/env sh

# the amount to increase / decrease each time
[ -z "$AMOUNT" ] && AMOUNT=5

# utility for sending notifications easily
notify() {
	notify-send "$@" -h string:x-dunst-stack-tag:'audioctl' -a 'audioctl'
}

# get current volume information
vol_str="$(wpctl get-volume @DEFAULT_AUDIO_SINK@)"

# Remove leading non-numeric or zero characters, then remove remaining non-numeric characters.
# NOTE: if zero (0.00), the string will be empty. This is fine for arithmetic operations.
vol_int="$(echo "$vol_str" | sed 's/^[^1-9]*//; s/[^0-9]//g')"

# if the string contains MUTED, set the variable accordion
case "$vol_str" in
*MUTED*) vol_off=1 ;;
*) vol_off=0 ;;
esac

# handle what action to perform from the argument
echo $vol_off
case $1 in
up) vol_int=$((vol_int + AMOUNT)) ;;
down) vol_int=$((vol_int - AMOUNT)) ;;
mute) vol_off=$((!vol_off)) ;;
*)
	echo 'E: could not decide what audio action to perform!' >&2
	notify 'could not decide what audio action to perform!' -u critical -t 5000
	exit 1
	;;
esac
vol_int=$((vol_int - (vol_int % AMOUNT)))
vol_pcnt=$(echo "scale = 2; $vol_int / 100;" | bc)

echo $vol_off
wpctl set-volume @DEFAULT_AUDIO_SINK@ "$vol_pcnt"
wpctl set-mute @DEFAULT_AUDIO_SINK@ "$vol_off"

play -n synth 0.005 sine 1000 vol 0.2 2>/dev/null

if [ "$vol_int" -eq 0 ] || [ "$vol_off" -eq 1 ]; then
	ico=audio-volume-muted
elif [ "$vol_int" -lt 33 ]; then
	ico=audio-volume-low
elif [ "$vol_int" -lt 66 ]; then
	ico=audio-volume-medium
else
	ico=audio-volume-high
fi

str="volume: $vol_int% $([ $vol_off -eq 1 ] && printf '(MUTE)')"
notify -i "$ico" -u low -h "int:value:$vol_int" "$str"
