#!/usr/bin/perl

#
# Chris Vanhoof <vanhoof@redhat.com>
# 
# Simple vmstat parser to csv including date
# Input file must be in the following format:
#	date ; vmstat
#
# ex: while true ; do date >> /tmp/vmstat.out ; vmstat >> /tmp/vmstat.out ; sleep <interval> ; done
#

use strict;
use Text::CSV;
use Benchmark;

my $input_file = $ARGV[0];

if (! $ARGV[0]){
	die("$0 -- must specify input file");
}

my $wc = `/usr/bin/wc -l $input_file`;
chomp($wc);

$wc =~ m/^(\d+)\s/;
my $line_count = $wc;
my $total_number_of_iterations = int($line_count / 4);

my $t0 = new Benchmark;

my @output_line_array;
my $csv = Text::CSV->new();

my $debug = 1;
my $iteration = 0;

my %percentage_shown_hash;

open(FILE, $input_file);
while (1){
	my $line_1 = <FILE>;
	my $line_2 = <FILE>;
	my $line_3 = <FILE>;
	my $line_4 = <FILE>; 

	if (! (($line_1) && ($line_2) && ($line_3) && ($line_4)) ) {
		last;
	}

	$iteration++;

	my $percent_done = int(($iteration / $total_number_of_iterations) * 100);

	if ((! ($percent_done % 5)) && (! $percentage_shown_hash{int($percent_done)}) ){
		print $percent_done."% of $input_file parsed..."."\n";
		$percentage_shown_hash{int($percent_done)} = 1;	
	}

	my @lines = ($line_1, $line_2, $line_3, $line_4);

	my @line_array;
	foreach my $line (@lines){
		if ($line =~ m/^\ \d+/){
			push(@line_array, $line);
		}
	}

	my @date_array = grep { m/^Mon/ or m/^Tue/ or m/^Wed/ or m/^Thu/ or m/^Fri/ or m/^Sat/ or m/^Sun/ ; } @lines;

	for (my $i = 0; $i < @line_array; $i++){
		chomp($date_array[$i]);
		chomp($line_array[$i]);
		$line_array[$i] =~ s/^\s+//msg;
		my @line_fragment_array = split(/\s+/, $line_array[$i]);
		$csv->combine($date_array[$i], @line_fragment_array);
		push(@output_line_array, $csv->string);
	}
}

open(FILE, ">$input_file.csv");
select(FILE);
print "date,r,b,swpd,free,buff,cache,si,so,bi,bo,in,cs,us,sy,id,wa"."\n";
print join("\n", @output_line_array);
close(FILE);

my $t1 = new Benchmark;
my $td = timediff($t1, $t0);

select(STDOUT);
print "$0 wrote: ".$input_file.".csv"."\n";
print "$0 took: ".timestr($td)."\n";
