#!/usr/bin/perl -w
# statbar: key-value-pairs visualised width bars
# "THE BEER-WARE LICENSE" (Revision 42):
# <bo@kbct.de> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return.

use strict;
use Getopt::Long;

my $width = `tput cols`;
my $showNumbers = 0;
GetOptions(
	'h' => \&usage,
	'width|w=i' => \$width,
	'n' => \$showNumbers
);

if ($#ARGV == -1) {
	if (! -t STDIN) {
		my @stdin = <STDIN>;
		@ARGV = (@ARGV, split(/\s+/, join(" ", @stdin)));
	}
	else {
		usage();
	}
}

my @names = [];
my @values = [];
my $maxnamelen = 0;
my $maxvalue = 0;

foreach my $i (0 .. $#ARGV) {
	($names[$i], $values[$i]) = split(':', $ARGV[$i]);
	if ($values[$i] !~ m/\d+/) {
		die "Values must be numbers.";
	}
	if (length $names[$i] > $maxnamelen) {
		$maxnamelen = length $names[$i];
	}
	if ($values[$i] > $maxvalue) {
		$maxvalue = $values[$i];
	}
}

my $maxBarWidth = $width - $maxnamelen - 2;	# 2 => " |"
if ($showNumbers) {
	$maxBarWidth -= 3 + length $maxvalue;	# 3 => " ()"
}
if ($maxBarWidth < 1) {
	die "Not enough space to display bars, increase width or choose shorter names";
}
my $factor = $maxvalue / $maxBarWidth;

for my $i (0 .. $#names) {
	if (length $names[$i] < $maxnamelen) {
		for (1 .. ($maxnamelen - length $names[$i])) {
			print " ";
		}
	}
	print $names[$i] . " |";
	for (1 .. ($values[$i] / $factor)) {
		print "#";
	}
	if ($showNumbers) {
		print " (" . $values[$i] . ")";
	}
	print "\n";
}

#
# usage()
#
sub usage {
	print <<EOS
Usage: $0 [-h] | [-w|width chars] key1:value1 [key2:value2 [...]]
Options:
  -h        : This help page
  -w|width  : Width of the output in chars (default `tput cols`)
  -n        : Print values behind the bars (default off)
EOS
;
	exit(1);
}

