#!/usr/bin/perl

use strict;

my %status;

my %config = (
	upsname => $ENV{upsname} || 'bertha',
	upshost => $ENV{upshost} || '127.0.0.1',
	upsc => $ENV{upsc} || 'upsc'
);

my %graph =  (
	'input_voltage' => {
				label => 'input',
				type => 'GAUGE',
				draw => 'LINE2'
			 },
	'output_voltage' => {
				label => 'output',
				type => 'GAUGE',
				draw => 'LINE2'
			 }
);

if ( exists $ARGV[0] and $ARGV[0] eq 'config' ) {
	my $s = $config{upsname};
	$s =~ s/_/ /g;
	if ($config{upshost} ne "127.0.0.1" && $config{upshost} ne "localhost") {
		$s .= " at $config{upshost}";
	}
	print "graph_title UPS Voltages - $s\n";
	print "graph_args -l 115\n";
	print "graph_vlabel Volts\n";
	foreach my $key (keys %graph) {
		print "$key.label $graph{$key}->{label}\n";
		print "$key.type $graph{$key}->{type}\n";
		print "$key.draw $graph{$key}->{draw}\n";
	}
} else {
	&fetch_values;
}

sub fetch_values {
	my $data = `$config{upsc} $config{upsname}\@$config{upshost}`;
	while ($data =~ /([a-z.]+): (.+)\b/g) {
		my $label = $1;
		my $value = $2;
		$label =~ s/\./_/g;
		$status{$label} = $value;
	}
	foreach my $label (sort keys %graph) {
		print "$label.value $status{$label}\n";
	}
}

