#!/usr/bin/perl -w

use strict;
use warnings;
use File::Basename;
use Cwd qw(abs_path);

# set current path of this command
my $curpath = dirname(Cwd::abs_path(__FILE__));

my $CONFFILE = "/etc/osw2csv.conf";
if (-f "$curpath/".basename($CONFFILE)) {
	require "$curpath/".basename($CONFFILE);
} elsif (-f $CONFFILE) {
	require $CONFFILE;
}

require "$curpath/osw2csv_functions";


unless (-p STDIN) {
	print STDERR <<"END_OF_USAGE";
usage:	# cat meminfofile | $0 > csvfile.csv
description:
	This script generate csv file, which is from "/proc/meminfo" output
	provided by OSWatcher or ExaWatcher.
	the meminfo output is read from STDIN, and cvs is provided onto STDOUT.
END_OF_USAGE
	exit 1;
}


# belows are defined in $COMMONFUNCTIONS
# $sys_bootsecond = 0;  # set by $zzz_second and the 1st "top -" line.
our $zzz_second;  # set by "zzz ... " line. 0 means "there are no zzz line"

# list of /proc/meminfo entries
our @meminfo_entries = ('Time','Timezone');


# get meminfo header, synchronized for analyzeMeminfoLine();
sub printMeminfoCSVHeader {
	print join(',', @meminfo_entries)."\n";
}


sub printMeminfoCSVBody {
	my $header_printed = 0; # T/F: whether header colmun has been printed

	# read/check the first line
	return if (!defined($_ = readNextLineFromSTDIN()));
	while (defined($_)) {
		# set current time if there is "zzz ***" line
		if (setZZZLine($_)) {
			$_ = readNextLineFromSTDIN();
			next;
		}

		# ignore if the line is not /^MemTotal:/
		# "MemTotal:" must be located on the 1st line of the meminfo,
		# otherwise it would be skipped.
		if ($_ !~ /^MemTotal:/) {
			$_ = readNextLineFromSTDIN();
			next;
		}
		my $date = getDateStringFromSeconds($zzz_second);
		my @meminfo_data = ($date,$ENV{TZ});
		while (defined($_)) {
			my $data = $_;
			$data =~ s/^[\w\(\)]+:\s*(\d+)\s*(|kB)$/$1/;
			last if ($data eq  $_);
			push(@meminfo_data, $data);
			if (!$header_printed) {
				my $entry = $_;
				$entry  =~ s/^([\w\(\)]+):\s*\d+\s*(|kB)$/$1/;
				push(@meminfo_entries, $entry)
			}
			$_ = readNextLineFromSTDIN(1);
		}

		if (!$header_printed) {
			printMeminfoCSVHeader;
			$header_printed = 1;
		}
		
		print join(',',@meminfo_data)."\n";
	}
}

printMeminfoCSVBody;
exit 0;


