#!/usr/bin/perl -w
#
# @package      hubzero-metrics
# @file         gen_tool_plots
# @author       Swaroop Samek <swaroop@purdue.edu>
# @copyright    Copyright (c) 2011-2015 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2011-2015 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) is free
# software: you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#
# =========================================================================
# This script generates the usage plot for simulation tools
#
# USAGE: ./gen_tool_plots [<YYYY-MM>]
#

use strict;
use DBI;
use Cwd;

use FindBin '$Bin';
my $filename = $Bin.'/includes/access.cfg';

our $hub_dir;
our $hub_db;
our $metrics_db;
our $db_host;
our $db_user;
our $db_pass;
do $filename;

my $mon;
my $year;
my $lmon;
our $graphdir = $hub_dir."/site/stats/chart_resources";
our $logplotgraph = $Bin.'/includes/xlogplotgraph';

my $dthis = shift();

if(!$dthis) {

        ($mon,$year) = (localtime)[4,5];
        $year += 1900;
        $mon++;
        $lmon = $mon-1;
        if ($mon == '1'){
                $year = $year-1;
                $lmon = '12';
        }
        $dthis = $year.'-'.sprintf("%02d", $lmon);
}

my $metrics_table = $hub_db.".jos_resource_stats_tools";
my $resource_table = $hub_db.".jos_resources";

my $dbhandle;
my $dbquery;
my $dbresult;
my (@totals);
my $sql;
my $title;
my $resid;

#  Open database...
$dbhandle = DBI->connect("DBI:mysql:database=$metrics_db;host=$db_host", $db_user, $db_pass);

# First find max date with data.
$sql = "SELECT max(datetime) FROM ".$metrics_table." WHERE datetime <= '".$dthis."-00'";
$dbquery = $dbhandle->prepare($sql)
   or die "Error:  can't prepare statement \"$sql\" ($dbhandle->errstr).\n";
$dbresult = $dbquery->execute
   or die "Error:  can't execute the query ($dbquery->errstr).\n";
while(@totals = $dbquery->fetchrow_array) {
   	$dthis = $totals[0];
}

# Find Title(label) for the plot
$sql = "SELECT DISTINCT(resid), res.title FROM ".$resource_table." res, ".$metrics_table." res_stats WHERE res.id = res_stats.resid AND restype=7 ORDER BY res.title";
$dbquery = $dbhandle->prepare($sql)
    or die "Error:  can't prepare statement \"$sql\" ($dbhandle->errstr).\n";
$dbresult = $dbquery->execute
    or die "Error:  can't execute the query ($dbquery->errstr).\n";
while(@totals = $dbquery->fetchrow_array) {
   	$resid = $totals[0];
   	$title = $totals[1];
	gen_plots($dbhandle, $metrics_table, $dthis, $title, $resid);
}

sub gen_plots {

	my $label;
	my $label_prefix;
	my @values = qw(Users Simulations Jobs Sessions tot_wall tot_cpu tot_view);
	foreach my $value (@values) {
		if($value eq "Users") {
			$label = "Simulation Users";
			$label_prefix = "# of "; 
		} elsif ($value eq "Simulations") {
			$label = "Simulation Sessions";
			$label_prefix = "# of "; 
		} elsif ($value eq "Jobs") {
			$label = "Simulation Runs";
			$label_prefix = "# of "; 
		} elsif ($value eq "Sessions") {
			$label = "Interactive Sessions";
			$label_prefix = "# of "; 
		} elsif ($value eq "tot_wall") {
			$label = "Wall Time (secs)";
			$label_prefix = "Total "; 
		} elsif ($value eq "tot_cpu") {
			$label = "CPU Time (secs)";
			$label_prefix = "Total "; 
		} elsif ($value eq "tot_view") {
			$label = "Interaction Time (secs)";
			$label_prefix = "Total "; 
		}
		plot_graph($dbhandle, $metrics_table, $dthis, $title, $resid, $label, $label_prefix, $value);
	}
}
sub plot_graph {

	my $sqm;
	my $dbquery1;
	my $dbresult1;
	my (@totals1);
	my $dbhandle;
	my $metrics_table;
	my $dthis;
	my $title;
	my $resid;
	my $label;
	my $label_prefix;
	my $value;
    	
	($dbhandle, $metrics_table, $dthis, $title, $resid, $label, $label_prefix, $value) = @_;

	my @periods = (0,1,3,12,13,14);
	foreach (@periods) {

		my $period = $_;

		if ( $period == '1' || $period == '12'  || $period == '14' ) {
       		$sqm = "SELECT CONCAT(SUBSTR(datetime,6,2),'/', LEFT(datetime,4)), ".$value." FROM ".$metrics_table." WHERE period='".$period."' AND resid='".$resid."' AND datetime <= '".$dthis."' AND ".$value." > 0 ORDER BY datetime";
		} elsif ( $period == '0' ) {
       		$sqm = "SELECT CONCAT(SUBSTR(datetime,6,2),'/', LEFT(datetime,4)), ".$value." FROM ".$metrics_table." WHERE resid = '".$resid."' AND period = '".$period."' AND (datetime LIKE '____-12-00%' OR datetime = '".$dthis."') AND datetime <= '".$dthis."' AND ".$value." > 0 ORDER BY datetime";
   		} elsif ( $period == '3' ) {
       		$sqm = "SELECT CONCAT(SUBSTR(datetime,6,2),'/', LEFT(datetime,4)), ".$value." FROM ".$metrics_table." WHERE resid = '".$resid."' AND period = '".$period."' AND (datetime LIKE '____-03-00%' OR datetime LIKE '____-06-00%' OR datetime LIKE '____-09-00%' OR datetime LIKE '____-12-00%' OR datetime = '".$dthis."') AND datetime <= '".$dthis."' AND ".$value." > 0 ORDER BY datetime";
   		} elsif ( $period == '13' ) {
     		$sqm = "SELECT CONCAT(SUBSTR(datetime,6,2),'/', LEFT(datetime,4)), ".$value." FROM ".$metrics_table." WHERE resid = '".$resid."' AND period = '".$period."' AND (datetime LIKE '____-09-00%' OR datetime = '".$dthis."') AND datetime <= '".$dthis."' AND ".$value." > 0 ORDER BY datetime";
		}
		
		#  Scripts being called
		my $logplotgraph = $main::logplotgraph;

		# Directory where graphs will be stored
                my $graphdir = $main::graphdir;
                my $file;
                my $filename=$graphdir."/hub.dat";
                my $line;
	
		my $ddate = substr($dthis,0,7);

		my $graphname;
		my $command;

		#print $sqm."\n";
		$dbquery1 = $dbhandle->prepare($sqm)
			or die "Error:  can't prepare statement \"$sqm\" ($dbhandle->errstr).\n";
		$dbresult1 = $dbquery1->execute
			or die "Error:  can't execute the query ($dbquery1->errstr).\n";

		open $file, '>', $filename
			or die "Can't open $file: $!";
		my @lines;
		while(@totals1 = $dbquery1->fetchrow_array) {
			push(@lines, "${totals1[0]} ${totals1[1]}");
		}
		foreach $line (@lines) {
			print { $file } "$line\n";
		}
		close $file;

		$graphname = $graphdir."/".$ddate."-".$period."-".$resid."-".$value;

		# getting rid of " in title as gnuplot complains
		$title =~ s/"/'/g;
		# getting rid of leading " - " in title
		$title =~ s/ - //g;

		my $title1;

		if (length($title) <= 18) {
			$title1 = $title." (".$value.")";
		} else {
			my $tmp = substr $title, 0, 18;
			$title1 = $tmp."... (".$value.")";
		}

		# gif
		# $command = $logplotgraph." -xdate -o '" . $graphname . "' -f gif -title \"" . $title1 . "\" -ylabel '".$label."' -xformat '%b%y' -b " . $filename. " 2> /dev/null";
		$command = $logplotgraph." -xdate -o '" . $graphname . "' -f gif -title \"" . $label . "\" -ylabel '".$label_prefix.$label."' -xformat '%b%y' -b " . $filename. " 2> /dev/null";

		system($command) == 0
			or die "Error: couldn't exec logplotgraph: $! $command";

		# postscript
		# $command = $logplotgraph." -xdate -o '" . $graphname . "' -f ps -title \"" . $title1 . "\" -ylabel 'Number of Users' -xformat '%b%y' -b " . $filename. " 2> /dev/null";

		# system($command) == 0
		#	or die "Error: couldn't exec logplotgraph: $! $command";

		#  Create the thumb of the graph
#		$graphname = "${graphname}-thumb";
#		system("$logplotgraph -xdate -o \"$graphname\" -f gif -thumbnail -b " . $graphdir . "/hub.dat") == 0
#   		or die "Error: couldn't exec logplotgraph: $!";

		# delete old plot data file
#		if(-e $graphdir . "/hub.dat") {
#			system("rm -f " . $graphdir . "/hub.dat");
#		}
		$dbquery1->finish;
	}
}

#  Close database...
$dbquery->finish;
$dbhandle->disconnect;

#  Delete any empty/failed graphs...
#system('find ' . $graphdir . ' -size 0 -exec rm {} \;');
