#!/usr/bin/env perl

#
## Author: gihnius@gmail.com
#

use warnings;
use strict;

my @nmons = @ARGV;
my %month_name = ("JAN"=>1, "FEB"=>2, "MAR"=>3, "APR"=>4, "MAY"=>5, "JUN"=>6, "JUL"=>7, "AUG"=>8, "SEP"=>9, "OCT"=>10, "NOV"=>11, "DEC"=>12);

foreach my $nmon (@nmons) {
    if ($nmon !~ /\.nmon$/) {
        print "$nmon may be not a nmon data!\n";
        next;
    }
    my (@cpu_idle, @mem_used, @month, @day, @hour, @min);
    open (NM,"< $nmon") or die "Can not open $nmon . $!";
    while (<NM>) {
        chomp;
        if (/^CPU_ALL/) {
            my @temp = split/,/;
            if ($temp[1] =~ /T\d+/) {
                push (@cpu_idle, 100.0 - $temp[5]);
            }
        }
        if (/^MEMNEW/) {
            my @temp = split/,/;
            if ($temp[1] =~ /T\d+/) {
                push (@mem_used, 100.0 - $temp[5]);
            }
        }
        if (/^ZZZZ/) {
            my @temp = split/,/;
            if ($temp[1] =~ /T\d+/) {
                if ($temp[2] =~ /(\d\d):(\d\d):\d\d/) {
                    push (@hour, $1);
                    push (@min, $2);
                }
                if ($temp[3] =~ /(\d\d)-([A-Z][A-Z][A-Z])-\d+/) {
                    push (@month, $month_name{$2});
                    push (@day, $1);
                }
            }
        }
    }                           ## end while
    close NM;
    my $len = @cpu_idle;
    $nmon =~ s/\.nmon//;
    my $save_file = $nmon . "_perf.txt";
    if ($len == ($#mem_used + 1) && $len == ($#month + 1) && $len == ($#day + 1) && $len == ($#hour + 1) && $len == ($#min + 1)) {
        open (OUT, ">> $save_file") or die "Can not open $save_file for writing $!";
        for (my $i = 0; $i < $len; $i++) {
            select OUT;
            ##output format: month day time(xx.xx) cpu_perf mem_use
            printf ("%2s\t%2s\t%2s.%2s\t%2.1f\t%2.1f\n", $month[$i], $day[$i], $hour[$i], $min[$i], $cpu_idle[$i], $mem_used[$i]);
        }
        close OUT;
    }
}