#!/usr/bin/env perl
#
# FILE:
# choplog
#
# FUNCTION:
# This is a Perl script to automatically extract run start 
# and stop times from the runlog, and use these to chop a 
# large logfile into per-run pieces.
#

# add a search path to find "timelocal.pl" and other required 
# bits and bytes on various oddly-installed machines.
# This is a hack, as the sysadmin really should install correctly, 
# but for now, this will hold water.
push (@INC, "/usr/local/lib/perl5/5.00501");
($inky = $0) =~ s/choplog//;
push (@INC, $inky);

# load the time handling utilities (in a path independent way)
require "utils.pl";


# print usage
if (2 > $#ARGV) {
	print "Usage: \n";
	print "$0 <file_prefix> <data_file> <timestamp_file> [<timestamp_file> [...]]\n";
	print "\n";
	print "\tSearch each <timestamp_file> for a start and end date,\n";
	print "\tthen extract text in between these dates from <data_file>.\n";
	print "\tEach extract is written to a file named <file_prefix>.<timestamp_file>\n";
	print "\n";
	print "\tTypically, the <timestamp_file>'s are the output of run.workload\n";
	print "\tand the <data_file> is the output of run.vmstat\n";
	die "\n";
}

# the chop file prefix name is in the first argument
$chop_prefix = shift;

# the file containing the data we want to analyze will be 
# the second argument.
$vmdata_file = shift;

print "Will chop up data file $vmdata_file\n";

# cycle over each file that contains timestamps
foreach $file (@ARGV) {
	print "Extracting start and stop times from $file \n";
 	open (FILE, $file) || warn "Can't open $file: $! \n";
	while (<FILE>) {
		# extract the time stamps from each file
		/rampup complete at time: (.*)/ && ($startdate = $1);
		/run complete at time: (.*)/ && ($enddate = $1);
	}
	close FILE;

	$startsecs = &maketime ($startdate);
	$endsecs = &maketime ($enddate);
	print "       Found start time $startdate\n";
	print "               end time $enddate\n";

	# create the output file name
	$outfile = $file;
	$outfile =~ s/^/>$chop_prefix./;
	print "       Will write chopped data to $outfile\n";
	open (CHOPFILE, $outfile) || die "Can't open $outfile: $!\n";

	# open the data file 
	open (VMDATA, $vmdata_file) || die "Can't open $vmdata_file: $! \n";

	# loop over records in the data file, copying them to the chop file
	$do_process = 0;
	while (<VMDATA>) {
		# grab the date string
		if (/^(=+)(\s+)(.+)/) {
			$datestring = $3;
			$secs = &maketime ($datestring);
			if ($secs > $startsecs) { $do_process = 1; }
			if ($secs > ($endsecs-615)) { $do_process = 0; }
		}
		if ($do_process) {
			print CHOPFILE $_;
		}
	}
	close VMDATA;
	close CHOPFILE;
	print "\n";
}
