#!/usr/bin/perl
#

use 5.006;
use CGI;
use DBI;
use TClubMD5;
use Fcntl ':flock';

my $server = "127.0.0.1";
my $user = $primary_user;
my $passwd = $primary_passwd;
my $dbase = $primary_dbase;
my $port = $primary_port;

my $timeshift = 7200;

my $query = new CGI;

print "Content-Type: text/html; charset=UTF-8\n\n";

my $eventtype = $query->param('eventtype');
my $mark = $query->param('mark');
my $program = $query->param('program');

my $who = $query->param('who');
my $token = $query->param('token');
my $ru_en = $query->param('l');

my $session = TClubMD5::md5_hex($who.$salt);

die("write_timestamp.pl: token is $token, session is $session!\n") if ($token ne $session);
die("psssooff!\n") if (in_list($who,$pssoff_guys_string));

my $browser = $ENV{'HTTP_USER_AGENT'};

my $ip = $ENV{'REMOTE_ADDR'};

my $messages_log = "/home2/clients/w_motiva/handlers/static/deltas";

my $delta = 0;

($dbase,$server,$port,$user,$passwd) = TClubMD5::get_connect_req($ru_en);

$dbconn=DBI->connect("dbi:Pg:dbname=$dbase;port=$port;host=$server",$user, $passwd);


if ($eventtype == 1) {
	$comm = "select extract(epoch from (current_timestamp - p_vremya_z)) from deltas where mark='$mark' and eventtype=0";
	&getTable;
	
#print STDERR $comm."!\n";

	$delta = sprintf("%.2f",${${$listresult}[0]}[0]) if ($ntuples == 1);
}

#create table deltas (proj_code text, addr text, mark text, program text, eventtype int2 default 0, p_vremya_z timestamp, delta float default 0.0);

my $cmd = "insert into deltas (proj_code, addr, mark, program, eventtype, p_vremya_z, delta) values ('$who','$ip','$mark','$program','$eventtype',current_timestamp,'$delta')";

#print STDERR $cmd."!\n";

my $result=$dbconn->prepare($cmd);
$result->execute;
&dBaseError($dbconn, $cmd) if (!defined($result));

&make_date($timeshift);
my $d = $thisdate.", ".$thistime;

my $m = "==============";
$m .= "\n".$who." at ".$d." = ".$ip." == ".$program." ====== ".$delta." === ".$browser."\n";
$m .= "==============\n\n";

&write_log_notification($m) if ($eventtype == 1);

$dbconn->disconnect;
$query->delete_all;
exit;

sub getTable {

	$result=$dbconn->prepare($comm);
    	$result->execute;
	&dBaseError($result, $comm."  (".$result->rows()." rows found)") if ($result->rows() ==
	-2);
	
	$listresult = $result->fetchall_arrayref;
	$ntuples = $result->rows();

};

sub dBaseError {

    my ($check, $message) = @_;
    print "<H4><FONT COLOR=BLACK><P>$message<BR>Error: ".$check->errstr."</FONT></H4>";
    die("Action failed on command:$message  Error_was:$DBI::errstr");
};

sub make_date 
{
my @months = (0,'January','February','March','April','May','June','July',
	       'August','September','October','November','December');
local ($addedtime) = @_;

    ($thissec,$thismin,$thishour,$mday,$mon,$thisyear,$t,$t,$t) = localtime(time+$addedtime);
    $mon++;
	 $month = $months[$mon];
	     $month = $$month if $$month;
    $thisyear += 1900;
    $current_date = "$month $mday $thisyear";
    
    if ($mday >= 10 && $mon >= 10 ) { $this_ = "$mon/$mday";}
    elsif ($mon >= 10) { $this_ = "$mon/0$mday";}
    elsif ($mday >= 10) { $this_ = "0$mon/$mday";}
    else { $this_ = "0$mon/0$mday";}

	$thisdate = "$thisyear/$this_";
    
    if ($thishour >= 10 && $thismin >= 10 ) { $thistime = "$thishour:$thismin";}
    elsif ($thishour >= 10) { $thistime = "$thishour:0$thismin";}
    elsif ($thismin >= 10) { $thistime = "0$thishour:$thismin";}
    else { $thistime = "0$thishour:0$thismin";}
}

sub write_log_notification {
my $text = shift;

open(OUTFILE, ">>$messages_log");

flock(OUTFILE,LOCK_EX);
select OUTFILE;
print $text."\n";
select(STDOUT);
flock(OUTFILE,LOCK_UN);
close OUTFILE;
}

sub in_list {
my $guy = shift;
my $str = shift;
my $comma = shift;

if (defined($comma)) {
return 1 if ($str eq $guy || $str =~ /^$guy\,/ || $str =~ /\,$guy\,/ || $str =~ /\,$guy$/);
return 0;
} else {
return 1 if ($str eq $guy || $str =~ /^$guy\#/ || $str =~ /\#$guy\#/ || $str =~ /\#$guy$/);
return 0;
}
}
