#!/bin/sh
set -e

argv0="$0"

# ADDING A NEW SOUND SERVER/CLIENT/WHATEVERIDK
# `volume a $2` must set the volume to $2, an integer value. This should be a
# percentage, 100% being the loudest possible volume that can be output by
# hardware without quality loss. Percentages above 100% will be allowable in
# software if using percentage units. If percentage units are implausible to
# implement, system units are okay (e.g. 0-$arbitrary scale versus 0-100).

# `volume s` must output the current volume in integer form in whatever units
# are being used by `volume a` on the given system.

VOLUME_TMP_FILE="$HOME/.volume-previous"

if uname | xargs strcmp NetBSD; then
	VOLUME_SYSTEM=netbsd
elif command -v pactl >/dev/null 2>&1; then
	VOLUME_SYSTEM=pulseaudio
else
	printf "%s: Unknown system.\n" "$0"
	exit 1
fi

usage(){
	printf "\
Usage: %b {function} (operand)\n" "$0"
	printf "\
Functions:
	'+'      - shortcut to \"relative \$2\"
	'-'      - shortcut to \"relative -\$2\"
	absolute - change sound output to absolute unit
	debug    - show debugging information
	help,''  - print this help output
	mute     - toggle mute/unmute
	relative - change sound output relative to current status
	status   - print current sound output in system unit \
"
	printf "\
The options are matched with [char]*. So \"%b help\"
works the same as \"%b h\".

" "$argv0" "$argv0"
	exit 1
}

case "$1" in

+) "$0" r  "$2" ;;
-) "$0" r -"$2" ;;

a*)
	str isvalue $2 && ! str isvalue $3 && str isdigit "$2" \
		|| usage
	"$0".$VOLUME_SYSTEM "$@"
	;;
s*)
	! str isvalue $2 \
		|| usage
	"$0".$VOLUME_SYSTEM s
	;;

d*)
	printf '$0: %s\nAudio system detected: %s\n' \
		"$0" \
		$VOLUME_SYSTEM
	;;

m*) ! str isvalue "$2" || usage
	# restore previous volume if there is one
	if test -e "$VOLUME_TMP_FILE"; then
		xargs "$0" a <"$VOLUME_TMP_FILE" \
			&& rm "$VOLUME_TMP_FILE" \
			&& printf "Unmuted.\n" \
			&& exit 0 \
			|| printf "Error restoring previous volume.\n" \
				1>&2 \
			&& exit 1
	fi

	# otherwise, make new file with previous volume

	# dd used rather than shell redirect so it's easy to determine
	# whether or not the file write worked
	if ! printf "%b" "$("$0" s)" \
				| dd of="$VOLUME_TMP_FILE" 2>/dev/null
	then
		printf "Error writing to file.\n" 1>&2
		exit 1
	fi

	# and then of course mute
	"$0" a 0
	printf "Muted.\n"

	exit 0 ;;

r*)
	str isvalue $2 && ! str isvalue $3 \
			&& str isdigit "$(printf "%s\n" "$2" | sed 's/^\-//')" \
		|| usage

	"$0" a \
		"$(printf "%s %s + p\n" \
				$("$0" s) \
				"$(printf "%s\n" $2 | tr - _)" \
			| dc)"
	exit $? ;;

*)	usage ;;
esac
