#!/usr/bin/perl
print "Content-type: text/html \n\n";

use IO::File;
use Socket;
use Time::localtime;
use Fcntl;
use strict;

my ($p,$p1,$p2,$p3,$line,$time_mark,$i,$j);
my ($total,$sum_len,$N_max);

#########################################################
# $total = Total request number;			#
# $sum_len = Total byte number;				#
# $N_max = Max line number in the file <visits.txt>	#
#########################################################

my $N_start=0;
my @rec;
my (@nam);				# array, retured with request

#########################################
# Yu. Semenov, September 2010		#
# Script is called by crontab	 	#
# reads files:				#
# <req_num.txt>, extracts the total     #
# records number and the total record	#
# length sum and write result to the	#
# file <visits.txt> in format:		#
# time_mark," ",$total," ",$sum_len	#
# the total line number in the output	#
# file is never more than $N_max=720	#
#########################################

$p="/home/httpd/htdocs/saturn/attacks/ids/req_num.txt";	# input file  <req_num.txt>
open(h_point,$p) or die "Can't start tst0: $!\n";

$p1="/home/httpd/htdocs/saturn/attacks/ids/visits.txt";	# output file <visits.txt>
sysopen(h_out, $p1,O_RDWR|O_CREAT) or die "Can't start tst1: $!\n";

$p2="/home/httpd/htdocs/saturn/attacks/ids/visits_1.txt"; # output file <visits_1.txt>
sysopen(h_out1, $p2,O_RDWR|O_TRUNC|O_CREAT) or die "Can't start tst2: $!\n";

$p3="/home/httpd/htdocs/saturn/attacks/ids/bytes.txt"; # output file <bytes.txt>
open(h_out2, "+>> $p3") or die "Can't start tst3: $!\n";

$N_max=720;				# 30 days
$time_mark=time;			# The time of this script execution
$line=readline(h_point);		# read line of <req_num.txt>
chomp($line);
close(h_point);
#print "L=",$line,"\n";
@nam=split(/\s/,$line);
$total=$nam[1];				# Total records for the last day
$sum_len=$nam[0];			# Total byte number for the last day
$i=0;
while(!eof(h_out))	{		# <visits.txt> development ######
    $rec[$i]=readline(h_out);		# REC-array creation		#
    $i++;								#
			}		#			#########
$rec[$i]=$time_mark." ".$total." ".$sum_len."\n";
#print "I=",$i," rec=",$rec[$i],"\n";

if($i>$N_max)	{$N_start=$i-$N_max;}
else{$N_start=0;}
for($j=$N_start;$j<$i+1;$j++)	{
print h_out1 $rec[$j];			# <visits1.txt> writing
			}
close(h_out1);

print h_out2 $time_mark," ",$sum_len,"\n";	# Write file bytes.txt
print h_out $time_mark," ",$total,"\n";         # Write file visits.txt

close(h_out);
close(h_out1);
close(h_out2);
close(h_point);
#print " T_m=",$time_mark," NNN=",$total," sum=",$sum_len,"\n";

exit(0);
