#!/usr/bin/perl

# ioregValues
# This script outputs (to STDOUT) the values of specified properties
# of an 'ioreg' object specified by name.
# The first command-line argument specifies the name of the 'ioreg' object.
# The second and subsequent command-line arguments specify the names of the
# properties for which values are to be reported.
# (If no second command-line argument is given,
#  it reports the values of all properties.)
# Sample usage:
#     ioregValues AppleSmartBattery CurrentCapacity MaxCapacity DesignCapacity
# The above would output the values for "CurrentCapacity", "MaxCapacity", and
# "DesignCapacity" of the 'ioreg' object named "AppleSmartBattery".
#
# Cameron Hayne (macdev@hayne.net)   March 2009

use strict;
use warnings;

sub getIoregValues($)
{
    my ($objectName) = @_;
    
    my %ioregValues = ();
    my $command = "/usr/sbin/ioreg -w 0 -r -n $objectName";
    open(IOREG, "$command |") or die "Failed to run '$command': $!\n";
    while(<IOREG>)
    {
        if (/^[\s|]*"(\w+)"\s*=\s*(.*)$/)
        {
            my $propertyName = $1;
            my $propertyValue = $2;
            $ioregValues{$propertyName} = $propertyValue;
        }
    }
    close(IOREG);
    return %ioregValues;
}

sub usageError($)
{
    my ($msg) = @_;
    
    print "Usage: $0 objectName [propertyName1] [propertyName2] [...]\n";
    die "$msg\n";
}

MAIN:
{
   usageError("") unless scalar(@ARGV) >= 1;
   my $objectName = shift @ARGV;
   my @propertyNames = @ARGV if @ARGV;
   
   my %ioregValues = getIoregValues($objectName);
   @propertyNames = sort(keys %ioregValues) unless @propertyNames;
   
   foreach my $propertyName (@propertyNames)
   {
       if (exists $ioregValues{$propertyName})
       {
           my $propertyValue = $ioregValues{$propertyName};
           print "$propertyName\t$propertyValue\n";
       }
   }
}

