#!/bin/bash

# Legacy battery monitor. I'm writing a better one, I should publish it some
# time.

level_critical=5
level_low=10
level_low_max_backlight=8

notif(){
	notify-send -a "Battery" "$@"
}

lower_backlight() {
	[ $(xbacklight -get) -le $level_low_max_backlight ] || xbacklight -set $(level_low_max_backlight)
}

while true; do
	now=$(cat /sys/class/power_supply/BAT0/energy_now 2>/dev/null)
	full=$(cat /sys/class/power_supply/BAT0/energy_full 2>/dev/null)

	if [ ! -z $now ] && [ ! -z $full ]; then
		percentage=$(( 100 * now / full ))
		echo "Current level: $percentage"

		if [[ "$(cat /sys/class/power_supply/BAT0/status 2>/dev/null)" != "Charging" ]]; then
			if [ $percentage -lt $level_critical ]; then
				notif -u "critical" "Power level critical" "Less than $percentage% remaining."
				lower_backlight
			elif [ $percentage -lt $level_low ]; then
				notif -t 59000 -u "critical" "Power supplies running low" "Less than $percentage% remaining."
				lower_backlight
			fi
		else
			if [ $percentage -ge 98 ]; then
				notif -t 10000 -u low "Fully charged" "Unplug charger."
			fi
		fi
	fi
	sleep '1m'
done
