#!/bin/sh

# Prints all batteries, their percentage remaining and a Nerd Font icon
# corresponding to charge status and level.

case $BLOCK_BUTTON in
	3) notify-send "󰁹 Battery module" "󰁹: full
󰂁: discharging
󰂄: charging
󰂃: not charging
󰂎: empty
󱃍: battery very low!
- Scroll to change adjust xbacklight." ;;
	4) xbacklight -inc 10 ;;
	5) xbacklight -dec 10 ;;
	6) setsid -f "$TERMINAL" -e "$EDITOR" "$0" ;;
esac

# Loop through all attached batteries and format the info. Match by type
# rather than a BAT?* name glob so Asahi's "macsmc-battery" is picked up too.
for battery in /sys/class/power_supply/*; do
	[ -r "$battery/type" ] && [ "$(cat "$battery/type")" = "Battery" ] || continue
	# If non-first battery, print a space separator.
	[ -n "${capacity+x}" ] && printf " "
	# Sets up the status and capacity
	capacity="$(cat "$battery/capacity" 2>&1)"
	charging_status="$(cat "$battery/status" 2>&1)"

	case "$charging_status" in
		"Full") status="󰁹" ;;
		"Charging") status="󰂄" ;;
		"Not charging") status="󰂃" ;;
		"Discharging")
			if [ "$capacity" -ge 95 ]; then
				status="󰁹"
			elif [ "$capacity" -ge 65 ]; then
				status="󰂀"
			elif [ "$capacity" -ge 40 ]; then
				status="󰁾"
			elif [ "$capacity" -ge 25 ]; then
				status="󰁼"
			elif [ "$capacity" -ge 10 ]; then
				status="󰁻"
			elif [ "$capacity" -ge 5 ]; then
				status="󰁺"
			else
				status="󰂎"
			fi
			;;
		"Unknown") status="󰂑" ;;
		*) exit 1 ;;
	esac
	# Will make a warn variable if discharging and low
	[ "$charging_status" = "Discharging" ] && [ "$capacity" -le 25 ] && warn="󱃍"
	# Low-battery notifications to dunst at 20/10/5%. State file avoids
	# re-notifying every refresh; only fires once per band while discharging.
	statefile="${XDG_CACHE_HOME:-$HOME/.cache}/sb-battery-band"
	if [ "$capacity" -le 5 ]; then band=5
	elif [ "$capacity" -le 10 ]; then band=10
	elif [ "$capacity" -le 20 ]; then band=20
	else band=0; fi
	prevband=$(cat "$statefile" 2>/dev/null) || prevband=0
	if [ "$charging_status" = "Discharging" ] && [ "$band" -ne 0 ] && [ "$band" != "$prevband" ]; then
		case "$band" in
			5) notify-send -u critical "󱃍 Battery critical" "$capacity% remaining -- plug in now" ;;
			10) notify-send -u critical "󰁺 Battery very low" "$capacity% remaining" ;;
			20) notify-send -u normal "󰁻 Battery low" "$capacity% remaining" ;;
		esac
	fi
	printf '%s' "$band" > "$statefile" 2>/dev/null
	# Prints the info
	printf "%s%s %d%%" "$status" "$warn" "$capacity"; unset warn
done && printf "\\n"
