#!/usr/bin/perl

# on_ac_power v 0.2
# Sunday 29 July 2001
# 
# on_ac_power utility replacement for PowerMac architecture
# exits with 0 if on AC power, with 1 if on batteries
# if on battery, outputs the percentage of battery left
#
# extension : if the -b or --battery switches are on, it outputs the battery
# status not depending on the AC status
#
# original version in the apmd distribution
# by Bastien Nocera <hadess@hadess.net>, 2001
# licensed under the GNU General Public License

#If file doesn't exist, assume we're on mains power
open(FILE, "/proc/pmu/info") || exit 0;

$matched = 0;
$ret_val = 0;

while (($line = <FILE>) && ($matched == 0)) {
	chop $line;
	if ($line =~ m/^AC\ Power/) {
		$matched = 1;
		if ($line =~ m/1$/) {
			# on AC
			$ret_val = 0;
		} else {
			# on battery
			$ret_val = 1;
		}
	}
}
close (FILE);

# on battery or "-b" or "--battery" ?
# we need to ouput the percentage of battery left
$arg = $ARGV[0];

if (($ret_val == 0) && !($arg =~ "-b") && !($arg =~ "--battery")) {
	exit $ret_val;
}

open(FILE, "/proc/pmu/battery_0") ||
	die ("No such file: /proc/pmu/battery_0");

while ($line = <FILE>) {
	chop $line;
	if ($line =~ m/^charge/) {
		@tmp = split(" ", $line);
		$charge = @tmp[2];
	}
	if ($line =~ m/^max_charge/) {
		@tmp = split(" ", $line);
		$max_charge = @tmp[2];
	}
}

print int($charge/$max_charge*100)."\n";
close (FILE);

exit $ret_val;
