#!/bin/sh
# -*- perl -*-
# This code allows us to start perl from our path or an environment variable
# rather than hardcoding a path into the #! line.  It works from sh or csh.
(exit $?0) && eval 'exec ${QPERLQ-perl} -x $0 ${1+"$@"}'
if (! $?QPERLQ) setenv QPERLQ perl
exec $QPERLQ -x $0 $argv:q

#!/usr/local/bin/perl -w
#
# $Id: apm_notify,v 1.2 1998/02/05 21:18:54 ejb Exp $
# $Source: /home/ejb/scripts/RCS/apm_notify,v $
# $Author: ejb $
#

require 5.002;
use strict;

my $whoami = ($0 =~ m,([^/\\]*)$,) ? $1 : $0;
#my $dirname = ($0 =~ m,(.*)[/\\][^/\\]+$,) ? $1 : ".";

my $search = $ENV{'SEARCH'} || "/home/ejb";
push(@INC, "$search/source/perl/modules");
require LinuxAPM;

if ((@ARGV == 1) && ($ARGV[0] eq "--help"))
{
    &usage(0);
}

my $apm_file = LinuxAPM::apm_file();
if (! -f $apm_file)
{
    print "$whoami: $apm_file does not exist; unable to get APM status\n";
    exit 0;
}

my $zephyr = 0;
my $interval = 30;
my $granularity = 10;
while (@ARGV)
{
    my $arg = shift(@ARGV);
    if ($arg eq "-z")
    {
	$zephyr = 1;
    }
    else
    {
	&usage(2);
    }
}
    
my $apm = new LinuxAPM;
my $last_plugged_in = undef;
my $last_percent = undef;
while (1)
{
    $apm->refresh();
    my $plugged_in = $apm->plugged_in();
    my $percent = $apm->percentage();

    my $message = "";

    if (defined $last_plugged_in)
    {
	if ($plugged_in != $last_plugged_in)
	{
	    $message .=
		"AC status changed from $last_plugged_in to $plugged_in\n";
	}
	if (int($percent / $granularity) != int($last_percent / $granularity))
	{
	    my $direction = "rose";
	    if ($percent < $last_percent)
	    {
		$direction = "dropped";
	    }
	    $message .=
		"Battery charge $direction from $last_percent to $percent\n";
	}
    }
    else
    {
	$message = +("Initial AC status: $plugged_in\n" .
		     "Initial battery charge: $percent\n");
    }

    if ($message ne "")
    {
	$message = "APM status change\n" . $message;
	if ($zephyr)
	{
	    my $user = $ENV{"LOGNAME"} or
		die "$whoami: can't get LOGNAME environment variable\n";
	    if (open(Z, "|zwrite -q -i postit $user"))
	    {
		print Z '@beep()' . $message;
		close(Z);
	    }
	}
	else
	{
	    print "\a", $message;
	}
    }

    $last_plugged_in = $plugged_in;
    $last_percent = $percent;

    sleep $interval;
}

sub usage
{
    my $status = shift;
    if ($status == 0)
    {
	open(OUT, ">&STDOUT");
    }
    else
    {
	open(OUT, ">&STDERR");
    }
    print OUT "Usage: $whoami [ -z ]\n";
    exit $status;
}
