#!/usr/bin/perl
#
#	apm status
#


use strict;
use RRDs;
umask 022;

chdir '/home/shin/rrdtool';
if ($ARGV[0] eq 'init') {
	&init;
	exit 0;
}

my($rrdtool) = '/usr/bin/rrdtool';
my(@f);
my($battery);
my($time);

open(APM, "/proc/apm");
@f = split(/\s+/,<APM>);
close APM;

chop $f[6];	# %$B$r<h$k(B
$time = 0;
$time = $f[7]/60 if ($f[8] =~ /^sec/);
$time = $f[7] if ($f[8] =~ /^min/);

RRDs::update("apm.rrd","N:$f[6]:$time");
my $ERR=RRDs::error;
	die "ERROR while updaing apm.rrd: $ERR\n" if $ERR;

if ($ARGV[0] ne 'graph') {
	exit 0;
}

# draw it
RRDs::graph("/home/shin/rrdtool/apm-day.png"
	,"--title","apm status"
	,"--start","-93600","-w", "500","-h" ,"150"
	,"DEF:remain=apm.rrd:remain:MAX",
	,"DEF:time=apm.rrd:time:MAX",
	,"AREA:remain#00FF00:\"%\"");
#	,"LINE1:time#0000FF:\"min\"");
RRDs::graph("/home/shin/rrdtool/apm-week.png"
	,"--title","apm status"
	,"--start","-12.5day","-w", "500","-h" ,"150"
	,"DEF:remain=apm.rrd:remain:MAX",
	,"DEF:time=apm.rrd:time:MAX",
	,"AREA:remain#00FF00:\"%\"");
#	,"LINE1:time#0000FF:\"min\"");
RRDs::graph("/home/shin/rrdtool/apm-month.png"
	,"--title","apm status"
	,"--start","-50day","-w", "500","-h" ,"150"
	,"DEF:remain=apm.rrd:remain:MAX",
	,"DEF:time=apm.rrd:time:MAX",
	,"AREA:remain#00FF00:\"%\"");
#	,"LINE1:time#0000FF:\"min\"");
RRDs::graph("/home/shin/rrdtool/apm-year.png"
	,"--title","apm status"
	,"--start","-732day","-w", "500","-h" ,"150"
	,"DEF:remain=apm.rrd:remain:MAX",
	,"DEF:time=apm.rrd:time:MAX",
	,"AREA:remain#00FF00:\"%\"");
#	,"LINE1:time#0000FF:\"min\"");

exit 0;


sub	init {
	RRDs::create("apm.rrd",
				"DS:remain:GAUGE:3000:U:U",
				"DS:time:GAUGE:3000:U:U",
                                "RRA:MAX:0.5:1:600",
                                "RRA:MAX:0.5:6:700",
                                "RRA:MAX:0.5:24:775",
                                "RRA:MAX:0.5:288:797",
                                "RRA:AVERAGE:0.5:1:600",
                                "RRA:AVERAGE:0.5:6:700",
                                "RRA:AVERAGE:0.5:24:775",
                                "RRA:AVERAGE:0.5:288:797" );
	my $ERR=RRDs::error;
		die "ERROR while creating apm.rrd: $ERR\n" if $ERR;
}
