#!/bin/sh

# depends on: awk, pactl, pacmd, notify-send

MAX_VOL=120
STEP=10

FILLED="■"
EMPTY="□"
STRIPPED="▨"

get_bar(){

    is_muted_$TARGET &&
        FILLED=$STRIPPED

    echo $1 | round | awk '{
            for (i=1;i <= $1/10;i++) {
                if ( i == 11 ) {
                    printf "|";
                }
                printf "'$FILLED'"
            };
            for (i=1;i <= 10-$1/10;i++) {
                printf "'$EMPTY'"
            };
        }'

}


notify(){
    volume=$(get_vol_$TARGET)
    bar=$(get_bar $volume)

    if is_muted_$TARGET ; then
        s="Muted"
    else
        s="Volume"
    fi

    s=$(echo "${TARGET} ${s}" | sed 's/^\(.\)/\U\1/')

    notify-send "${s}: ${volume}%" "$bar" --app-name=volumesh

}

round(){
    awk '{
        print int($1/'$STEP')*'$STEP';
    }'
}

round_vol(){
    rounded=$(get_vol_$TARGET | round)
    newvol=$(min $MAX_VOL $rounded)
}

min(){
    printf '%i\n' ${@} | sort -n | head -n1
}

# Pulse{{{
get_vol_pulse(){
    env LC_ALL=C pactl list sinks |
        awk '/^\tVolume/ {
                gsub(/%/,"");
                printf $5;
            }'
}

is_muted_pulse(){
    env LC_ALL=C pacmd list-sinks | grep 'muted: yes' 1> /dev/null
}

change_vol_pulse(){
    pactl set-sink-volume @DEFAULT_SINK@ "${1}$(min 120 $2)%"
    round_vol
    pactl set-sink-volume @DEFAULT_SINK@ "${newvol}%"
}

toggle_mute_pulse(){
    pactl set-sink-mute @DEFAULT_SINK@ toggle
}
#}}}
# Mpd {{{

get_vol_mpd(){
    env LC_ALL=C mpc vol |
        sed -e 's/^.*://g' -e 's/%.*$//g'
}

is_muted_mpd(){
    env LC_ALL=C mpc status | grep '\[paused\]' 1> /dev/null
}
change_vol_mpd(){
    mpc vol "${1}${2}"
    round_vol
    mpc vol "${newvol}"
}

toggle_mute_mpd(){
    mpc toggle
}
#}}}
usage(){
    local CNAME=`basename $0`
    echo "${CNAME} [-d][-di <amount>]"
    echo "${CNAME} [-d][-t]"
    echo ""
    echo "Options:"
    echo "  -m --mpd          Target mpd instead of PulseAudio"
    echo "  -i --increase     <amount> of volume to increase"
    echo "  -d --decrease     <amount> of volume to decrease"
    echo "  -t --toggle       Mute/Unmute target"
    echo "  -h --help         Show This help message"

    exit "$1"
}
TARGET=pulse

# test $# = 0 &&
    # usage 1

while [ $# -gt 0 ]
do
    case $1 in
        -m | --mpd)
            TARGET=mpd
            shift
            ;;
        -i | --increase)
            shift
            change_vol_$TARGET + $1
            shift
            ;;
        -d | --decrease)
            shift
            change_vol_$TARGET - $1
            shift
            ;;
        -t | --toggle)
            toggle_mute_$TARGET
            shift
            ;;
        -h | --help)
            usage 0
            ;;
        *)
            usage 1
            ;;
    esac
done

notify

# vim: fdm=marker
