#!/bin/bash

# lockmute.sh - Mute sound output while GNOME is locked.

STATE_FILE=~/.lockmute_state
gdbus monitor -y -d org.freedesktop.login1 |
    while read -r DBUS_OUTPUT ; do
        LOCK_STATE=$(echo "$DBUS_OUTPUT" | grep -o "'LockedHint': <\w*>" | awk '{print $2}')
        if [[ "$LOCK_STATE" == "<true>" ]]; then
            AUDIO_STATE=$(amixer get Master | grep -o '\[\(on\|off\)\]')
            if [[ "$AUDIO_STATE" == *"[off]"* ]]; then
                echo "WAS_MUTED" > "$STATE_FILE"
            else
                echo "WAS_NOT_MUTED" > "$STATE_FILE"
            fi
            amixer set Master mute > /dev/null
        elif [[ "$LOCK_STATE" == "<false>" ]]; then
            if [[ "$(cat "$STATE_FILE")" == "WAS_NOT_MUTED" ]]; then
                amixer set Master unmute > /dev/null
            fi
            rm "$STATE_FILE"
        fi
    done