#!/bin/bash
# Steven Maresca
# lightyear4 @t gmail.com
#
# Parses Battery information out of /proc/acpi tree
# and returns percentage of battery life available at
# runtime
#
# Requires ACPI of course, awk, and perl
#
# Are there better ways to do this? Sure. However, this simply worked for me.
#
# calculates battery capacity using specs for the design capacity
# (i.e. the capacity it should have when coming new from the factory)
# this a) allows you to keep track of (eventual) battery degradation
# as it ages.  if you wish to use the 'last full capacity' to calculate
# battery life, simply change the assignment of CAPACITY to use "full" 
# intead of "design."
#
# This version greatly cleaned up from the first which, frankly, was probably my first shot
# at shell scripting, all that time ago. This script works with batteries of all capacities
# and all systems with perl and awk (but I think one would be hard pressed to find such a
# system nowadays anyway).  Easily updated to work purely with the shell, but it was
# written as you see it for my convenience.  If it serves your purpose, then by all means
# grab it and use as you wish.  Email me any questions or comments.
#
# Current version of this script (and others) always available
# at http://www.fugitivethought.com/projects/shell-scripts/
#
# Start battstat script

# grabs the ACPI reported value for current battery capacity
# this is field three on the line spit out by grep, which
# awk outputs by itself
BATTERY_REMAINING=`grep remaining /proc/acpi/battery/BAT0/state | awk '{print $3}'`

# grabs the ACPI reported value for fresh-from-the-factory full capacity.
# I prefer using this value because it gives you a heads for battery deterioration;
# if the highest reported value seems to plateau at some value <100%, it implies 
# that your battery is dying.  Alas.  
FULL_CAPACITY=`grep "design capacity:" /proc/acpi/battery/BAT0/info | awk '{print $3}'`

# Heres the actual calculation part. This just assigns the variable whatever value
# perl outputs from the calculation. 
PERCENT_LEFT=`perl -e "print $BATTERY_REMAINING/$FULL_CAPACITY*100"`

# Perl in its anal retentive nature will output the percentage, plus 15 or so digits
# to the right of the decimal...which arent needed.  This portion truncates the output 
# and makes it more useful to humans.
PERCENT_TRIM=`expr substr "$PERCENT_LEFT" 1 4`

# Now we're done! Spit out the result and exit
echo $PERCENT_TRIM %

# end battstat script
