#!/bin/sh -e
#
#  battery: print the state of the battery
#  Copyright (C) 2009 Raphaël Pinson.
#
#  Authors: Raphaël Pinson <raphink@ubuntu.com>
#           Dustin Kirkland <kirkland@canonical.com>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, version 3 of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

PKG="byobu"
color 2>/dev/null || color() { true; }

search () {
	local str expr
	str="$1"
	expr="$2"
	echo "$str" | sed -n "s/${expr}/\1/p"
}


if [ "$1" = "--detail" ]; then
	for bat in /proc/acpi/battery/*; do
		cat "$bat/info"
		cat "$bat/state"
	done
	exit 0
fi

for bat in /proc/acpi/battery/*; do
	# make sure that this battery is present
	infofile=$(cat "$bat/info")
	present=$(search "$infofile" "present: *\(.*\)")
	[ "${present}" = "no" ] && continue

	# obtain full and remaining battery values
	statefile=$(cat "$bat/state")
	full=$(search "$infofile" "last full capacity: *\(.*\) m[AW]h")
	rem=$(search "$statefile" "remaining capacity: *\(.*\) m[AW]h")

	percent=$( echo "$rem" "$full" | awk '{printf "%.0f",  100*$1/$2}')
	if [ "$percent" -lt 33 ]; then
		color="$(color R k)"
		bcolor="$(color b R k)"
	elif [ "$percent" -lt 67 ]; then
		color="$(color Y k)"
		bcolor="$(color b Y k)"
	else
		color="$(color G k)"
		bcolor="$(color b G k)"
	fi
	percent="$percent%"

	state=$(search "$statefile" "charging state: *\(.*\)")
	case $state in
		charging)
			sign="+"
		;;
		discharging)
			sign="-"
		;;
		charged)
			sign="="
			percent=
		;;
		*)
			sign="$state"
		;;
	esac
	printf "$bcolor%s$(color -)$color|%s|$(color -) " "$percent" "$sign"
	break
done
