#!/bin/sh

# Prints all batteries, their percentage remaining and an emoji corresponding
# to charge status (🔌 for plugged up, 🔋 for discharging on battery, etc.).

case $BLOCK_BUTTON in
    3) notify-send "🔋 Battery module" "🔋: discharging
🛑: not charging
🔄;: stagnant charge
🔌: charging
⚡: charged
❗: battery very low!" ;;
esac

# Loop through all attached batteries.
for battery in /sys/class/power_supply/BAT?
do
	# Get its remaining capacity and charge status.
	capacity=$(cat "$battery"/capacity 2>/dev/null)
	if [ -n "$capacity" ]; then
		#do not print misreads
		[ "$capacity" -gt 100 ] &&
			echo "Error. Capacity:$capacity" > /dev/stderr &&
			continue
		# do not display full batteries (nice to unclutter status bars for laptops mostly used stationiary)
		[ "$capacity" -eq 100 ] &&
			printf '\n' &&
			continue

		unset status
		status=$(sed "s/Not charging/🛑/" "$battery"/status)
		# Center picture around the actual capacity.
		# Displayable capacities: 0, 1/4, 1/2, 3/4, 1 -> intervall of length 25% centered around displaycategory
		# -> +- 12.5% for every level
		if grep -qE "(Discharging|Charging)" "$battery"/status; then
			status=
			[ "$capacity" -le 87 ] &&
				status=""
			[ "$capacity" -le 63 ] &&
				status=""
			[ "$capacity" -le 37 ] &&
				status=""
			[ "$capacity" -le 13 ] &&
				status=""
			[ "$capacity" -le 5 ] &&
				status="❗"
			if grep -q "Charging" "$battery"/status; then
				status="${status}🔌"
			fi
		fi
		printf "%s \n" "$status"
	else
		echo "Error. Capacity:$capacity" > /dev/stderr #if battery fails during reading, quit
	fi
done