#!/usr/bin/perl

# Author: Andrew Theurer
#
# usage: sysfs-postprocess <dir>  dir = directory where sysfs.txt can be found
#
# The purpose of this script is to
# -output the chart data in JSON format (sysfs.js)
# -output html file (sysfs.html) with embedded javascript, using d3.js libraries
#
# The input file that this scripts processes must be in the format which is generated by sysfs-datalog

use strict;
use warnings;

use lib $ENV{'pbench_lib_dir'};
no lib ".";
use GenData qw(gen_data);

my $dir=$ARGV[0];
my %sysfs;
my $file;
my $timestamp;
my $timestamp_ms;
my $line;
my $count;
my $value;

open(SYSFS_TXT, "$dir/sysfs-stdout.txt") || die "could not find $dir/sysfs-stdout.txt\n";
while (my $line = <SYSFS_TXT>) {
	chomp $line;
	# timestamp: 1404854661.042987923
	# /sys/module/cpuidle_kvm/parameters/poll_cnt: 0
	# /sys/module/cpuidle_kvm/parameters/halt_cnt: 18288
	# /sys/module/cpuidle_kvm/parameters/exit_cnt: 0

	if ( $line =~ /^timestamp:\s(\d+\.\d+)/ ) {
		$timestamp = $1;
		$timestamp_ms = 1000 * $timestamp;
		next;
	}

	if ($line =~ /(\S+):\s(\d+)/ ) {
		$file = $1;
		$value = $2;
		$file =~ s/^\///;
		$file =~ s/\//-/g;
		$sysfs{sysfs}{sysfs}{$file}{$timestamp_ms} = $value;
	}
}
close(SYSFS_TXT);

my %graph_threshold;
my %graph_type;
gen_data(\%sysfs, \%graph_type, \%graph_threshold, $dir);

