#!/usr/bin/env bash

# Dependencies:
# - amixer
# - pactl
# - jq
# - libnotify

ACTION=$1

get_volume_info() {
    amixer sget Master | \
        grep 'Left:' | \
        sed -e 's/[^[]*\[\([0-9]*\)%\][^[]\[\(\w*\)\]/{"volume": \1, "muted": \2}/' \
            -e 's/on/false/' \
            -e 's/off/true/'
}

notify() {
    notify-send "$1" "$2" -e -t 1500 -h string:x-canonical-private-synchronous:volume
}

mute() {
    pactl set-sink-mute @DEFAULT_SINK@ toggle

    VOLUME_INFO=$(get_volume_info)
    VOLUME=$(echo $VOLUME_INFO | jq .volume)
    if [ $(echo $VOLUME_INFO | jq .muted) == "true" ]
    then
        AUDIO_ICON="󰝟"
        MUTED_STR="Muted"
        BODY=""
    else
        AUDIO_ICON="󰕾"
        MUTED_STR="Unmuted"
        BODY=$(echo "$VOLUME%")
    fi

    TITLE=$(echo "$AUDIO_ICON $MUTED_STR")
    notify "$TITLE" "$BODY"
}

set_volume() {
    # Set the volume
    TARGET=$1
    pactl set-sink-volume @DEFAULT_SINK@ $TARGET

    # Send a notification
    VOLUME_INFO=$(get_volume_info)
    ACTION=$([[ ${TARGET:0:1} == "+" ]] && echo "Volume Up" || echo "Volume Down")
    VOLUME=$(echo $VOLUME_INFO | jq .volume)

    if [ $(echo $VOLUME_INFO | jq .muted) == "true" ]
    then
        AUDIO_ICON="󰝟"
        MUTED_STR="[muted]"
    else
        AUDIO_ICON="󰕾"
        MUTED_STR=""
    fi

    TITLE=$(echo "$AUDIO_ICON $ACTION")
    BODY=$(echo "$VOLUME% $MUTED_STR")
    notify "$TITLE" "$BODY"
}

case $ACTION in
    mute)
        mute
        ;;
    set)
        set_volume $2
        ;;
    *)
        echo "Unknown action"
        exit 1
        ;;
esac

