#! /bin/sh
# Log apm battery percentage
# Synopsis:
# 'powerlog INTERVAL [device1] [device2]' 
# 'powerlog off' ( kills all logging processes )
# device default is /dev/console (e.g. connected to an xterm -C)
# To do: when terminating, how to prevent cron from mailing to root ?

# This values change with battery aging :
CUT=18			# 'cutoff' apm % when the machine powerfails
U=72			# how many seconds lasts 1 apm %
# Defaults which are overwritten by cmdline:
INTERVAL=30	  # minimal logging frequency (seconds) 
DEV1=/dev/console # default output device
DEV2=""		  # opional output device
LOG=/var/log/power.log
header="powerlog starting:"
footer=":powerlog terminating."
# If you don't want to log to file, uncomment this: 
# LOG=""

[ $2 ] && DEV1=$2
[ $3 ] && DEV2=$3

case $1 in

    off) # Terminate xterm-console and all powerlog processes
        kill `ps ax | grep 'xterm -C' | grep -v grep | cut -d" " -f2` 2>/dev/null;
	echo $footer > $DEV1;
	[ $LOG ] && echo $footer >> $LOG;
        killall powerlog 2>/dev/null;
	exit 0 
    ;;

    *) 	# go logging
	echo $header > $DEV1;
	[ $DEV2 ] && echo $header > $DEV2;
	[ $LOG ] && echo $header > $LOG;
	# quiet fallback to default minimum...
	[ "$1" -ge "$INTERVAL" ] && INTERVAL=$1;
	# logging cycle:
	while true; do
	actual=`cat /proc/apm | cut -d " " -f 7 | tr --delete "%"`;
	# guess remaining minutes 
	rmain=$((($actual-$CUT)*$U/60));
	log="
`date +%H:%M:%S`...`apm -m` [remaining: $rmain min]
";
	echo $log > $DEV1;
	[ $DEV2 ] && echo $log > $DEV2;
	[ $LOG ] && echo $log >> $LOG;
        sync;
	sleep $INTERVAL;
	# Uncomment this if you like to log recharging:
	if on_ac_power; then powerlog off; fi;
	done
    ;;

esac
