From 547c9fe458915a9e51c46c0e47e4b340af149c0f Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Fri, 21 Mar 2025 14:28:32 +0100
Subject: [PATCH] Improve volume setting script.

---
 testing/home/desktop/.local/bin/vol | 54 ++++++++++++++++++++++++++---
 1 file changed, 49 insertions(+), 5 deletions(-)

diff --git a/testing/home/desktop/.local/bin/vol b/testing/home/desktop/.local/bin/vol
index 80f427d..2872d91 100755
--- a/testing/home/desktop/.local/bin/vol
+++ b/testing/home/desktop/.local/bin/vol
@@ -1,8 +1,52 @@
 #!/bin/sh
-if [ "$1" = "m" ]; then
-    pacmd set-sink-mute 0 1
-elif [ "$1" = "u" ]; then
-    pacmd set-sink-mute 0 0
+set -e
+
+MAX_LOUDNESS=150
+
+BIN_NAME="$(basename $0)"
+FLAG_HELP_SHORT='-h'
+FLAG_HELP_LONG='--help'
+
+print_usage() {
+    echo "Usage: ${BIN_NAME} [${FLAG_HELP_SHORT}] [${FLAG_HELP_LONG}] [LOUDNESS]"
+    echo "Set audio volume, or (if called without any arguments) toggle audio device muteness.\n"
+    echo "Available arguments (of which at most one may be used):\n"
+    echo "  LOUDNESS  audio volume to set (as percentage, must be integer)"
+    echo "  ${FLAG_HELP_SHORT}, ${FLAG_HELP_LONG}   display this help and exit"
+}
+
+error_exit() {
+    echo "Aborting due to $1\n"
+    print_usage
+    exit 1
+}
+
+toggle_mute() {
+    if [ "$(pactl get-sink-mute 0)" = "Mute: no" ]; then
+        MUTE_BOOL=1
+    else
+        MUTE_BOOL=0
+    fi
+    pacmd set-sink-mute 0 "${MUTE_BOOL}"
+}
+
+set_vol_percentage() {
+    AT_FULL=65536
+    pacmd set-sink-volume 0 $(calc "($1 * ${AT_FULL} // 100)")
+}
+
+N_MAX_ARGS=1
+if [ "$#" -gt "${N_MAX_ARGS}" ]; then
+    error_exit "number of arguments greater ${N_MAX_ARGS}"
+elif [ -z "$1" ]; then
+    toggle_mute
+elif [ -z "$(echo -n $1 | sed 's/[0-9]*//g')" ]; then
+    if [ "$1" -gt "${MAX_LOUDNESS}" ]; then
+        error_exit "demand for unreasonably high loudness: $1."
+    fi
+    set_vol_percentage "$1"
+elif [ "$1" = "$FLAG_HELP_SHORT" ] || [ "$1" = "$FLAG_HELP_LONG" ]; then
+    print_usage
 else
-    pacmd set-sink-volume 0 $(calc "($1 * 65536 // 100)")
+    error_exit "unrecognized argument: $1"
 fi
-- 
2.30.2