#!/bin/bash

[ ! -d /proc/acpi ] && exit 0

LOW_SOUND="/etc/acpi/sounds/low_battery.wav"
CRITICAL_SOUND="/etc/acpi/sounds/battery_critical.wav"
SHUTDOWN_SOUND="/etc/acpi/sounds/shutdown.wav"
PLAY_SOUND="/usr/bin/aplay -N"
POWEROFF="/etc/acpi/powerbtn.sh"

BATCAPACITY=`cat /proc/acpi/battery/BAT0/info | grep "^design capacity:" | cut -b26- | cut -f1 -d\ `

WARN_LOW=1
WARN_CRITICAL=1

while [ 1 ] ; do
	BATSTATE=`cat /proc/acpi/ac_adapter/ADP0/state | grep "^state:" | cut -b26-`
	if [ $BATSTATE = "off-line" ] ; then
		BATLEVEL=`cat /proc/acpi/battery/BAT0/state | grep "^remaining capacity:" | cut -b26- | cut -f1 -d\ `
		BATPERCENT=`expr 100 \* $BATLEVEL / $BATCAPACITY`
		if [ $BATPERCENT -lt 3 ] ; then
			$PLAY_SOUND $SHUTDOWN_SOUND 2> /dev/null
			sleep 2
			source $POWEROFF
			sleep 30
		elif [ $BATPERCENT -lt 6 ] ; then
			if [ -n "$WARN_CRITICAL" ] ; then
				WARN_CRITICAL=
				$PLAY_SOUND $CRITICAL_SOUND 2> /dev/null
			fi
			sleep 6s
		elif [ $BATPERCENT -lt 10 ] ; then
			if [ -n "$WARN_LOW" ] ; then
				WARN_LOW=
				$PLAY_SOUND $LOW_SOUND 2> /dev/null
			fi
			sleep 10s
		elif [ $BATPERCENT -lt 20 ] ; then
			sleep 20s
		else
			sleep 30s
		fi
	else
		WARN_LOW=1
		WARN_CRITICAL=1
		sleep 30s
	fi
done

