#!/bin/dash
FONT="10x20"
FLAG=/tmp/batt-low
SAFE_SHUTDOWN_CAPACITY=2
SAFE_SHUTDOWN_FLAG=/tmp/batt-low-monitor

### helpers

# check if ac adapter is attached
is_online() {
	grep -q on-line /proc/acpi/ac_adapter/*/state || 
	grep -q 1 /sys/class/power_supply/*/online 
}

# get remaining capacity
getcap() {
	cat /sys/class/power_supply/*/capacity  | head -n 1
}

# monitor battery and shutdown safely is battery is too low
safe_shutdown() {
	[ -f $SAFE_SHUTDOWN_FLAG ] && exit # only run one instance
	> $SAFE_SHUTDOWN_FLAG
	while ! is_online; do
		if [ $(getcap) -lt $SAFE_SHUTDOWN_CAPACITY ]; then
			poweroff noprompt
			exit
		fi
		sleep 5 # batt is already low, don't waste more by checking too often
	done
	rm -f $SAFE_SHUTDOWN_FLAG
	exit
}


############# main ############

# no warning needed if AC adapter is attached
is_online && exit

# type of message
case $1 in
	critical)
		TYPE=critical
		MG=50 BG=red FG=white TEXT="Battery is critical, shutdown imminent.\nAttach charger now."
		safe_shutdown &
		;;
	low|*)
		TYPE=low
		MG=30 BG=yellow FG=black TEXT="Battery is low.\nPlease attach charger."
		;;		
esac

# only show the message once
FLAG=$FLAG-$TYPE
[ -f $FLAG ] && exit
> $FLAG

# display
if type yaf-splash > /dev/null; then
	# preferred UI
	TEXT=$(printf "$TEXT\n\nClick here to remove this message.")
	yaf-splash -font "$FONT" -outline 0 -margin $MG -bg $BG -fg $FG -text "$TEXT"
else
	# alternative UI
	Xdialog --title "Battery Low" --msgbox "$(printf "$TEXT")" 0 0
fi

# cleanup
rm -f $FLAG
