#!/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 netstatfile | $0 > csvfile.csv
description:
	This script generate csv file, which is from "netstat -i" output
	provided by OSWatcher or ExaWatcher.
	the netstat output is read from STDIN, and cvs is provided onto STDOUT.
	This could analyze "netstat -i" only.
END_OF_USAGE
	exit 1;
}



# belows are defined in /usr/bin/osw2csv_functions
our $zzz_second;  # set by "zzz ... " line. 0 means "there are no zzz line"

# for "netstat -i"
#     header array for Iface
my @ifheaderary = ();
#    interface array which should be shown for "netstat -a -i -n"
my @ifary = ();

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


# analyze the Iface line, configure @ifheaderary at only the first call
# ex. "Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg"
sub analyzeIfaceLine {
	my $line = $_[0];

	return if ($line !~ /^Iface\s+/);
	my @ary = split(/\s+/, $line);
	shift @ary;
	if (!$header_printed) {
		@ifheaderary = @ary;
		return;
	}
	my ($cur, $saved) = (join(',',@ary), join(',',@ifheaderary));
	if ($cur ne $saved) {
		warning("Iface header differs, believe saved one:",
			"  Current: $cur",
			"  Saved  : $saved");
	}
}


# analyze each interface line
# ex. "bondeth0 1500 0 55029512 0 672921 0 49800084 0 0 0 BMmRU
sub analyzeEachInterfaceLine {
	my ($line) = @_;
	return if ($line =~ /- no statistics available -/); # skip alias if
	my @ret = split(/\s+/, $line);
	my $ifname = shift(@ret);
 	if (!$header_printed) {
		push(@ifary, $ifname);
	} else {
		if (!grep(/^$ifname$/, @ifary)) {
			warning("new interface($ifname) appeared, skip...");
		}
	}
	return @ret;
}


# print interface csv header
sub printIfaceCSVHeader {

	my @outputary = ();
	foreach my $if (@ifary) {
		map { push(@outputary, "$if $_") } @ifheaderary;
	}
	print "Time,Timezone,";
	print join(',', @outputary)."\n";
	$header_printed = 1;
}


sub printNetstatCSVBody {
	# read/check the first line

	# skipcommas is ",,,,," which will be inserted if the iface is skipped
	my $skipcommas = "";
	return if (!defined($_ = readNextLineFromSTDIN()));
	while (defined($_)) {
		# set current time if there is "zzz ***" line
		if (setZZZLine($_)) {
			$_ = readNextLineFromSTDIN();
			next;
		}

		# check /^Time ##:##:##/ or /^\s*<##/##/#### ##:##:##>/ line
		if (setZZZByTimeLine($_)) {
			$_ = readNextLineFromSTDIN();
			next;
		}
		# ignore if the line is not /^Iface\s+MTU\s+/
		unless (/^Iface\s+MTU\s+/) {
			$_ = readNextLineFromSTDIN();
			next;
		}

		# analyze "Iface " line just for saving headers
		analyzeIfaceLine($_);
		$_ = readNextLineFromSTDIN();

		# set skipcommas
		if (!$header_printed) {	
			my @ary = map { ""; } @ifheaderary; 
			$skipcommas = join(',', @ary);
		}
		my $date = getDateStringFromSeconds($zzz_second);
		my @output = ($date,$ENV{TZ});
		my @ifarytmp = @ifary;
		# analyze "<Interface> mtu met rx-ok rx-err ..." line
		# note that there is a brige named "0abc8c00", not only "eth#"
		# FIXME: This simply uses "Ip:" as a terminator of netif list
		while (defined($_) && /^([\d\w:\.]+)/ && !/^Ip:\s*$/) {
			my $newif = $1;
			if (!$header_printed) {
				# in case @ifary is not set
				push(@output, analyzeEachInterfaceLine($_));
				$_ = readNextLineFromSTDIN();
				next;
			}
			if (/- no statistics available -/) {
				# skip alias interfaces
				$_ = readNextLineFromSTDIN();
				next;
			}
			# in case $header_printed(=@ifary is set)
			if (!grep(/^$newif$/, @ifarytmp)) {
#				warning("found unknown if($newif), skip...");
				$_ = readNextLineFromSTDIN();
				next;
			}
			my $curif = shift(@ifarytmp);
			while ($curif ne $newif) {
				# if some ifs are disappeared, add $skipcommas
#				warning("no '$curif' found in this loop, fill it with '$skipcommas'");
				$curif = shift(@ifarytmp);
				push(@output, $skipcommas);
			}
			push(@output, analyzeEachInterfaceLine($_));
			$_ = readNextLineFromSTDIN();
		}

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

printNetstatCSVBody;
exit 0;

