#!/usr/bin/perl
## hpsum-plot.pl
###
###     this script scans the working directory for data dirs left behind
###	by previous invocations of hpsum, and then interactively lets the
###	user choose which data he/she would like plotted in gnuplot
###
#

$DIRPREFIX=".hpsum-";
$OLDDIR=$ENV{PWD};

###
###		End customizable variables
###

##
##		First, let's get a list of all .hpsum directories, and let the
##		user choose at which one to look
##

open (HPSDIRS, "ls -d ${DIRPREFIX}* 2>/dev/null |") || die ("can't do an ls -d: $!");
@dirlist=<HPSDIRS>;
close HPSDIRS;

$i=1; @tmplist=@dirlist; $size=@dirlist;
if (! $size) {
print "$0:\nI didn't find any acceptable directories, so\n";
print "I'm cowardly exiting.\n";
exit -1;
}

print "I found the following directories, please select one:\n";
while(@tmplist) { printf("%d:\t%s", $i++, shift @tmplist); } 
print "choice: ";
$line = <STDIN>;
$line =~ s/[^0-9]+//g;
chomp $line;
while ( ! $line || $line < 0 || $line > @dirlist) {
print "1-${size}, please: ";
$line = <STDIN>;
$line =~ s/[^0-9]+//g;
chomp $line;
}
chomp $dirlist[$line-1];
$chosendir = $dirlist[$line-1];

##
##		Now, let's grab the first file we see, and see what was counted in it
##

open (FILES, "ls -1 ${chosendir}/*.*.hpsum |") || die ("can't do an ls -1: $!");
@filelist=<FILES>;
$testfile = shift @filelist;
close FILES;

open (DFILE, $testfile) || die "$!";
@datafile=<DFILE>;
close DFILE;

$doneyet=0;
while(! $doneyet){
	$line = shift @datafile;
	( $time, $null, $null, $null, $counttype ) = split(/:/, $line, 6);
	if($time > 0) { $doneyet = 1; }
	else { push @counted, $counttype; }
}

##
##		Now let's show the user what we found, and have him/her choose
##		what he/she would like to see.
##

$i=0; @tmplist=@counted; 
print "these are the acceptable datatypes found:\n";
while(@tmplist) { printf("%d:\t%s\n", $i++, shift @tmplist); } 

print "enter a type, or list of types separated by commas, or q to quit:\n";
print "(and incorrect entries will be filtered out silently)\n";
print "choice(s)> ";
$line = <STDIN>;
$line =~ s/\s//g;
if ( $line eq "q\n" ) { exit 0; }
$line =~ s/,[^0-9]+,/,/g;
$line =~ s/[,]*[^0-9,]+[,]*//g;
@choices = split (/,/, "$line" );

while(@choices) {
	$foo = shift @choices;
	push @selected, @counted[$foo];
}


##
##		Now we set up the script to be used by gnuplot, and for the
##		time being we're writing it to a temp file in /tmp/gnuplot<pid>,
##		and then we run gnuplot.
##
$i=0;
while($i < @selected){
	if(! $plotcmd) { $plotcmd = "p "; }
	else { $plotcmd = "$plotcmd, "; }
	$plotcmd = "$plotcmd \"< grep -h @selected[$i] ${chosendir}/*.*.hpsum | awk -F: '{ print \$1,\$7 }'\" u 1:2 t \"@selected[$i++]\"";
}
$plotcmd = "${plotcmd}; pause -1;";

open(FINAL, ">/tmp/gnuplot$$");
print FINAL "$plotcmd\n";
close FINAL;

system "gnuplot -persist /tmp/gnuplot$$";
system "rm /tmp/gnuplot$$";
