home · contact · privacy
Improve volume setting script. master
authorChristian Heller <c.heller@plomlompom.de>
Fri, 21 Mar 2025 13:28:32 +0000 (14:28 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Fri, 21 Mar 2025 13:28:32 +0000 (14:28 +0100)
testing/home/desktop/.local/bin/vol

index 80f427d596d0053e8a94862b163ebab63c223d54..2872d915d12419a662c169f083c01705ff043244 100755 (executable)
@@ -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