#!/usr/bin/env bash
#
# Read battery status in Linux
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

batteries=$(upower --enumerate | grep BAT)

function generate_battery_update {
    local battery_path=$1
    local battery_status=$(upower --show-info "$battery_path")
    local battery_state=$(grep 'state:' <<<"$battery_status" | awk '{print $2}')
    local battery_percentage=$(grep 'percentage:' <<<"$battery_status" | awk '{print $2}')
    battery_percentage=${battery_percentage%\%}
    set +e
    local time_remaining=$(grep 'time to empty:' <<<"$battery_status" | sed 's/\W*time to empty:\W*//g')
    local tooltip="$time_remaining until empty"
    if [ -z "$time_remaining" ]; then
        time_remaining=$(grep 'time to full:' <<<"$battery_status" | sed 's/\W*time to full:\W*//g')
        if [ -z "$time_remaining" ]; then
            tooltip="fully charged"
        else
            tooltip="$time_remaining until full"
        fi
    fi
    set -e
    local battery_icon=""
    local class=""

    if [ $battery_state = "charging" ]; then
        if [ $battery_percentage -eq 100 ]; then
            battery_icon="⚡"
        else
            battery_icon="⚡"
        fi
    elif [ $battery_percentage -le 12 ]; then
        battery_icon="⚠"
    elif [ $battery_percentage -le 25 ]; then
        battery_icon="▁"
    elif [ $battery_percentage -le 37 ]; then
        battery_icon="▂"
    elif [ $battery_percentage -le 50 ]; then
        battery_icon="▃"
    elif [ $battery_percentage -le 62 ]; then
        battery_icon="▄"
    elif [ $battery_percentage -le 75 ]; then
        battery_icon="▅"
    elif [ $battery_percentage -le 87 ]; then
        battery_icon="▆"
    elif [ $battery_percentage -lt 100 ]; then
        battery_icon="▇"
    else
        battery_icon="█"
    fi

    if [ $battery_percentage -le 15 ]; then
        class="critical"
    elif [ $battery_percentage -le 30 ]; then
        class="warning"
    fi
        jq --unbuffered --compact-output <<EOF
{
"text":"${battery_percentage}% ${battery_icon}",
"tooltip":"$tooltip",
"percentage":${battery_percentage},
"class":"${class}"
}
EOF
}

while read bat; do
    generate_battery_update "$bat"
done<<<"$batteries"

upower --monitor | grep --line-buffered 'device changed:' | while read l; do
    while read bat; do
        generate_battery_update "$bat"
    done<<<"$batteries"
done
