#!/usr/bin/env bash
# Sends a desktop notification when the charger is plugged in or unplugged,
# with the current battery percentage.
#
# Listens to udev power_supply events rather than polling, so the notification
# shows up the moment the cable goes in or out. Events also fire for battery
# level changes, so it only notifies when the charger's online state flips.

ac=$(grep -l '^Mains$' /sys/class/power_supply/*/type 2>/dev/null | head -n1)
bat=$(ls -d /sys/class/power_supply/BAT* 2>/dev/null | head -n1)
[[ -z $ac || -z $bat ]] && { echo "charger-notify: no charger or battery found, exiting"; exit 0; }
ac=${ac%/type}

last=$(<"$ac/online")
udevadm monitor --udev --subsystem-match=power_supply | while read -r _; do
    now=$(<"$ac/online")
    [[ $now == "$last" ]] && continue
    last=$now
    capacity=$(<"$bat/capacity")
    if [[ $now == 1 ]]; then
        icon=battery-good-charging title="🔌 Charger connected"
    else
        icon=battery-good title="🔋 Charger disconnected"
    fi
    # The synchronous hint replaces the previous notification instead of stacking.
    notify-send -a "Battery" -i "$icon" -h string:x-canonical-private-synchronous:charger \
        "$title" "Battery at $capacity%"
done
