#!/usr/bin/env bash

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

ACTION=$1

get_brightness() {
    brightnessctl | \
        grep "Current brightness" | \
        sed -e 's/^\s\+Current brightness: [0-9]\+ (\([0-9]\+\)%).*$/\1/'
}

get_kb_brightness() {
    brightnessctl -d platform::kbd_backlight | \
        grep "Current brightness" | \
        sed -e 's/^\s\+Current brightness: [0-9]\+ (\([0-9]\+\)%).*$/\1/'
}

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

set_brightness() {
    # Set the brightness
    TARGET=$1
    brightnessctl set $TARGET > /dev/null

    # Send a notification
    BRIGHTNESS=$(get_brightness)
    ACTION=$([[ ${TARGET:0:1} == "+" ]] && echo "Brightness Up" || echo "Brightness Down")

    BRIGHTNESS_ICON="󰃠"

    TITLE=$(echo "$BRIGHTNESS_ICON $ACTION")
    BODY=$(echo "$BRIGHTNESS%")
    notify "$TITLE" "$BODY"
}

set_kb_brightness() {
    # Set the brightness
    TARGET=$1
    brightnessctl -d platform::kbd_backlight set $TARGET > /dev/null

    # Send a notification
    BRIGHTNESS=$(get_kb_brightness)
    ACTION=$([[ ${TARGET:0:1} == "+" ]] && echo "Keyboard brightness Up" || echo "Keyboard brightness Down")

    BRIGHTNESS_ICON="󰃠"

    TITLE=$(echo "$BRIGHTNESS_ICON $ACTION")
    BODY=$(echo "$BRIGHTNESS%")
    notify "$TITLE" "$BODY"
}


case $ACTION in
    set)
        set_brightness $2
        ;;
    kb_set)
        set_kb_brightness $2
        ;;
    *)
        echo "Unknown action"
        exit 1
        ;;
esac

