#!/bin/sh -e

icon_dir="${XDG_DATA_HOME:-$HOME/.local/share}/icons/notifications"
volume_step=0.05

_notify_volume() {
	volume="$(wpctl get-volume @DEFAULT_AUDIO_SINK@ | awk '{print $2*100}')"
	notify-send -u normal -t 1000 -a "Volume control" \
		-h string:synchronous:audio \
		-h string:x-canonical-private-synchronous:audio \
		-h int:value:"$volume" \
		-i "${icon_dir}/speaker.png" \
		"Volume" "${volume}%"
}

_notify_mute() {
	if ! (printf "SINK\nSOURCE" | grep -q -F "$1"); then
		return 1
	fi

	status="$(wpctl get-volume @DEFAULT_AUDIO_"$1"@ | awk '{print $2*100 ":" $3}')"
	volume="$(printf "%d" "${status%%:*}")"

	class="$([ "$1" = "SINK" ] && printf "Sound" || printf "Microphone")"
	icon="$([ "$1" = "SINK" ] && printf "speaker.png" || printf "microphone.png")"
	state="$([ "${status##*:}" = "[MUTED]" ] && printf "muted" || printf "unmuted")"

	notify-send -u normal -t 2000 \
		-i "${icon_dir}/${icon}" \
		"${class} ${state}" "Volume: ${volume}%"
}

case "$1" in
	--toggle)
		wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle
		_notify_mute SINK
		;;
	--toggle-source)
		wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle
		_notify_mute SOURCE
		;;
	--increase)
		wpctl set-volume @DEFAULT_AUDIO_SINK@ "${volume_step}+"
		_notify_volume
		;;
	--decrease)
		wpctl set-volume @DEFAULT_AUDIO_SINK@ "${volume_step}-"
		_notify_volume
		;;
	*)
		cat <<-EOF
		Usage: volumecontrol [--increase|--decrease|--toggle|--toggle-source]
		    --increase     : Increase volume of default sink by $volume_step
		    --decrease     : Decrease volume of default sink by $volume_step
		    --toggle       : Toggle mute state of default sink
		    --toggle-source: Toggle mute state of default source
		EOF
		exit 1
		;;
esac
