#!/bin/bash
# normally, would just use acpi,
# but it doesn't work well for multiple batteries
# (e.g. thinkpads)

BATS=/sys/class/power_supply/BAT*/

function query() {
    # query a numerical value for multiple batteries
    # and echo their sum
    result=$(cat $BATS/$1)
    echo "$result" | paste -sd+ | bc
}

if [[ $1 == 'mon' ]]; then
    while true; do
        battery_level=$(batt percent)
        if [ $battery_level -le 15 ] && ([[ $(batt status) == "Discharging" ]] || [[ $(batt status) == "Not charging" ]]); then
            notify-send --urgency=critical "Battery low" "Battery level is ${battery_level}%!"
        fi
        sleep 120
    done

elif [[ $1 == 'status' ]]; then
    echo $(cat $BATS/status | grep -E "Discharging|Charging|Not charging|Full")

elif [[ $1 == 'percent' ]]; then
    STATUS=$(batt status)
    if [[ $STATUS == "Full" ]]; then
        printf "100"
    else
        ENERGY_FULL=$(query energy_full) # mWh
        ENERGY_NOW=$(query energy_now)   # mWh
        PERCENT=$(echo "$ENERGY_NOW/$ENERGY_FULL * 100" | bc -l)
        printf '%.0f\n' $PERCENT
    fi
fi
