#!/usr/bin/env zsh
LC_CTYPE="en_US.UTF-8"
set -x
charging_status () {
    cat /sys/class/power_supply/BAT0/status
}

battery_percentage () {
    ibam --percentbattery | grep -Pom 1 '\d{1,3}'
}

if [[ "$(charging_status)" == "Charging" ]] && \
   [[ $(battery_percentage) -gt 5 ]] && \
   [[ -f /run/user/${UID}/battery_low ]]; then
        logger "Power reconnected and above 5 percent, clearing nofication state."
        rm /run/user/${UID}/battery_low
        for id in $(dunstctl history | jq '.data[0][] | select(.summary.data == "LOW BATTERY!")| .id.data' \
                                     | tee /tmp/dunst_history.json); do
            dunstify --close=${id}
        done
elif [[ "$(charging_status)" == "Discharging" ]] && \
         [[ $(battery_percentage) -le 5 ]] && \
         [[ ! ( -f /run/user/${UID}/battery_low ) ]] ; then
        logger "Low power!  Triggering notification...."
        dunstify --urgency=critical \
                 --icon=/usr/share/icons/breeze-dark/emblems/16/emblem-warning.svg \
                 'LOW BATTERY!' \
                 'Battery level is low, plug power quick!'
        touch /run/user/${UID}/battery_low
fi

set +x
# vim:  ft=zsh

