#!/bin/sh

# add your volume and mute attributes here (mixerctl -af /dev/mixer?)
_volumelist="outputs.master outputs.play"
_mutelist="outputs.master.mute outputs.play_mute"

[ -z $1 ] && print "$0 [volume]" && exit 2

_mute() {
    # $1 = device
    # $2 = on/off
    for _entry in $_mutelist;
    do
        if mixerctl -f $1 2>&1 | cut -d"=" -f1 | grep -q $_entry;
        then
            print "$1: $_entry => $2"
            mixerctl -qf $1 $_entry=$2
        fi
    done
}

_vol() {
    # $1 = device
    # $2 = volume
    for _entry in $_volumelist;
    do
        if mixerctl -f $1 2>&1 | cut -d"=" -f1 | grep -q $_entry;
        then
            print "$1: $_entry => $2"
            mixerctl -qf $1 $_entry=$2
        fi
    done
}

for _mixdev in /dev/mixer*;
do
    # do not follow symlinks (eg. /dev/mixer)
    [ -h $_mixdev ] && continue

    # if volume is 0 set volume and mute
    # if volume is >0 set volume and unmute
    if [ "$1" == "0" ]; then
        _mute $_mixdev on
        _vol $_mixdev 0
    elif [ "$1" -gt "0" ] && [ "$1" -lt "1001" ]; then
        _mute $_mixdev off
        _vol $_mixdev $1
    else
        print "Use number between 0 and 1000"
        exit 1
    fi
done

printf "VOL\n" >> /tmp/lemonbar.fifo
