#!/usr/bin/perl
#acpi_monitor.pl 20031021
#troy@zenux.net

# cat /proc/acpi/battery/CMB0/state
# present:                 yes
# capacity state:          ok
# charging state:          charging
# present rate:            1528 mW
# remaining capacity:      669 mWh
# present voltage:         15655 mV

#dumb hack
$ENV{'DISPLAY'} = ':0.0';

my %acpi;
my $msgfile				= '/tmp/acpi_warn.txt';
my $bat					= '/proc/acpi/battery/CMB0/state';
my $warn_level			= 400;
my $shutdown_level		= 90;
my $shutdown_delay		= 45;
my $msg_command			= '/usr/bin/gedit';
my $play_command		= '/usr/bin/play';
my $shutdown_command	= '/sbin/poweroff';
my $warn_sound			= '/usr/share/sounds/email.wav';
my $shutdown_sound		= '/usr/share/sounds/shutdown1.wav';
my $audible				= 1;


open(A,$bat) or die "Can't read $bat $!\n";
while (<A>) {
    s/\s+//g;
    my ($key, $val) = split /:/;
    $acpi{$key} = $val;
}
close A;

my $trigger = $acpi{'remainingcapacity'};
$trigger =~ s/\D//g;

if ($trigger < $shutdown_level) {
    warnme($trigger,"Shutdown in $shutdown_delay seconds\nrm $msgfile to abort shutdown.");
    shutmedown();
} elsif ($trigger < $warn_level) {
    warnme($trigger);
}


sub warnme
{
    my $mw = shift;
    my $msg = shift;
    open (OUT,">$msgfile") or die "Can't open $msgfile: $!\n";
    print OUT "Warning: $mw mWh left\n$msg\n";
    close OUT;
    
    playmsg($warn_sound) if $audible;
    system($msg_command,$msgfile);
}

sub shutmedown
{
    playmsg($shutdown_sound) if $audible;
    sleep($shutdown_delay);
    if (-f $msgfile) {
        system($shutdown_command);
    }
}

sub playmsg
{
    my $sound=shift;
    system($play_command,$sound);
}