#!/usr/bin/perl -w
# @package      hubzero-metrics
# @file         xlogfix_middleware_cpu
# @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 copies over the simulation tool data from middleware logs
#
# USAGE: ./xlogimport_middleware_cpu
#

use lib '/opt/DBI/lib/site_perl/5.6.1/sun4-solaris';
use lib '/opt/Data-ShowTable/lib/site_perl/5.6.1';
use lib '/opt/DBD-mysql/lib/site_perl/5.6.1/sun4-solaris';
use lib '/opt/mysql/lib/mysql';
use strict;
use DBI;

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

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

my $debug;
my $dbhandle;
my $dbsthandle;
my $dbrowvalues;
my @dbrow;
my $mw_handle;
my $mw_sthandle;
my $mw_rowvalues;
my @mw_row;
my $statement;
my $dt;
my $user;
my $ip;
my $tool;
my $execunit;
my $cputime;

$debug = 0;

my $exclude_users = "'gridstat'";

#  Open database...
#-------------------
#print "Opening Middleware database...\n";
$mw_handle = DBI->connect("DBI:mysql:$hub_db:$db_host", $db_user, $db_pass);
#print "Opening usage statistics database...\n";
$dbhandle = DBI->connect("DBI:mysql:$metrics_db:$db_host", $db_user, $db_pass);

#  Select all Middleware records...
#--------------------------------
#print "Finding all Middleware records...\n";
$statement = "SELECT joblog.start, sessionlog.username, sessionlog.remoteip, sessionlog.appname, sessionlog.exechost, joblog.cputime FROM joblog, sessionlog WHERE joblog.sessnum = sessionlog.sessnum AND sessionlog.username NOT IN (".$exclude_users.") AND sessionlog.username NOT LIKE 'hctest%' ORDER BY joblog.start, sessionlog.username, sessionlog.remoteip";
$mw_sthandle = $mw_handle->prepare($statement)
  or die "Error:  can't prepare statement \"$statement\" ($mw_handle->errstr).\n";
$mw_rowvalues = $mw_sthandle->execute
  or die "Error:  can't execute the query ($mw_sthandle->errstr).\n";

#  Select all toolstart records already imported from Middleware...
#----------------------------------------------------------------
#print "Finding all toolstart records already imported from Middleware...\n";
$statement = "SELECT id, datetime, user, ip, tool, execunit, cputime FROM toolstart ORDER BY datetime, user, ip";
$dbsthandle = $dbhandle->prepare($statement)
  or die "Error:  can't prepare statement \"$statement\" ($dbhandle->errstr).\n";
$dbrowvalues = $dbsthandle->execute
  or die "Error:  can't execute the query ($dbsthandle->errstr).\n";

#print "Importing Middleware records into usage database...\n";
@dbrow = $dbsthandle->fetchrow_array;
while(@mw_row = $mw_sthandle->fetchrow_array) {
	$dt = $mw_row[0];
	$user = $mw_row[1];
	$ip = $mw_row[2];
	$tool = $mw_row[3];
	$execunit = $mw_row[4];
	$cputime = $mw_row[5];

	#  If no ending datetime, mark cputime as unknown...
	#-----------------------------------------------------
	if($cputime && $cputime < 0) {
		$cputime = -1;
	}
	else {
		$cputime = int($cputime + .5);
	}

	#  Advance toolstart pointer up to Middleware ponter...
	#----------------------------------------------------
	while( @dbrow
	   && ($dbrow[1] lt $dt
	   || ($dbrow[1] eq $dt && $dbrow[2] lt $user)
	   || ($dbrow[1] eq $dt && $dbrow[2] eq $user && $dbrow[3] lt $ip)) ) {
		@dbrow = $dbsthandle->fetchrow_array;
	}

	#  Check for an existing toolstart record...
	#--------------------------------------------
	if(@dbrow && $dbrow[1] eq $dt && $dbrow[2] eq $user && $dbrow[3] eq $ip) {

		#  If toolstart record is incomplete, check Middleware record for an update...
		#---------------------------------------------------------------------------
		if($dbrow[6] <= 0 && $cputime > 0) {
			$statement = "UPDATE toolstart SET cputime = " . $dbhandle->quote($cputime)
			   . " WHERE id = " . $dbhandle->quote($dbrow[0])
		}
		else {
			$statement = "";
		}
		@dbrow = $dbsthandle->fetchrow_array;
	}
	else {

		#  If no existing toolstart record,
		#  Do nothing as are just importing CPUtimes
		#-------------------------------------------------------
	}
	if($statement) {
		if($debug > 1) {
			print $statement . "\n";
		}
		elsif(!$debug) {
			$dbhandle->do($statement)
			  or die "Error:  can't execute statement \"$statement\" ($dbhandle->errstr).\n";
		}
	}
}


#  Close database...
#--------------------
#print "Closing databases...\n";
$dbsthandle->finish;
$mw_sthandle->finish;
$dbhandle->disconnect;
$mw_handle->disconnect;

