#!/usr/bin/env sh

# A simple script to adjust the volume
# Requires pulse and amixer


function drawBar(){
	local percent="$1";

	for i in {1..10}; do
		local boxPercent=$(($i*10))
		if [ "$boxPercent" -lt "$percent" ]; then
			echo -n "■"
		elif [ "$boxPercent" -eq "$percent" ]; then
			echo -n "■"
		elif [ "$(($boxPercent-10))" -lt "$percent" ]; then
			echo -n "▣"
		else
			echo -n "□"
		fi
	done

}

case "$1" in
	"up")
		if type -p pulseaudio-ctl 2> /dev/null; then
			pulseaudio-ctl up
		else
			amixer -q -D default sset Master 5%+ unmute
		fi
		;;
	"down")
		if type -p pulseaudio-ctl 2> /dev/null; then
			pulseaudio-ctl down
		else
			amixer -q -D default sset Master 5%- unmute
		fi
		;;
	"toggle")
		if type -p pulseaudio-ctl 2> /dev/null; then
			pulseaudio-ctl mute
		else
			amixer -q -D default sset Master toggle
		fi
esac

if type -p pulseaudio-ctl 2> /dev/null; then
	volume="$(pulseaudio-ctl full-status | cut -d ' ' -f1)"
	speakerStatus="$(pulseaudio-ctl full-status | cut -d ' ' -f2 | sed 's/no/on/g')"
else
	volume="$(amixer -D default sget Master | grep -o '\[.*\%'  | head -n 1 | tr -d '[%')"
	speakerStatus="$(amixer -D default sget Master | grep -o '\[\(on\|off\)'  | head -n 1 | tr -d '[')"
fi


if [[ "$speakerStatus" == "on" ]]; then
	command -v notify-send && notify-send -R "/tmp/volume" "Volume" "$(drawBar $volume) ${volume}%"
else
	command -v notify-send && notify-send -R "/tmp/volume" "Volume" "Muted"
fi