#!/usr/bin/env bash
# Sends a desktop notification when the battery drops to 15%, 10% and 5% while
# discharging. Each threshold fires once per discharge; plugging in re-arms them.
#
# Starting (or resuming) already below a threshold doesn't replay every level
# passed on the way down: only the lowest one reached is announced, and the
# ones above it are marked as done.
#
# Polls sysfs rather than listening to UPower, since the capacity only moves
# about 1% a minute and this keeps it to plain shell (same as vpn-notify).

INTERVAL=30
THRESHOLDS=(15 10 5) # highest first

bat=$(ls -d /sys/class/power_supply/BAT* 2>/dev/null | head -n1)
[[ -z $bat ]] && { echo "battery-notify: no battery found, exiting"; exit 0; }

declare -A notified # threshold -> 1 once announced this discharge

notify() {
    local level=$1 capacity=$2 icon urgency title body
    case $level in
        15) icon=battery-low     urgency=normal   title="🔋 Battery low" ;;
        10) icon=battery-caution urgency=normal   title="🪫 Battery low" ;;
        5)  icon=battery-empty   urgency=critical title="🪫 Battery critically low" ;;
    esac
    body="$capacity% remaining. Plug in your charger."
    [[ $level == 5 ]] && body="$capacity% remaining. Plug in now, or the laptop will shut down soon."
    notify-send -a "Battery" -i "$icon" -u "$urgency" "$title" "$body"
}

while true; do
    capacity=$(<"$bat/capacity")
    status=$(<"$bat/status")

    if [[ $status == Charging || $status == Full ]]; then
        notified=()
    else
        # Find the lowest threshold reached that hasn't been announced yet.
        lowest=""
        for t in "${THRESHOLDS[@]}"; do
            ((capacity <= t)) && [[ -z ${notified[$t]} ]] && lowest=$t
        done
        if [[ -n $lowest ]]; then
            notify "$lowest" "$capacity"
            # Mark it and everything above it as done.
            for t in "${THRESHOLDS[@]}"; do
                ((t >= lowest)) && notified[$t]=1
            done
        fi
    fi

    sleep "$INTERVAL"
done
