#!/perl/bin/perl -w
#$|=1;
use strict;

# Переменные
my ( $secn,$minn,$hourn,$dayn,$monn,$yearn ) = '';	# Переменные для определения даты и времени
my ( $str, $name, $val, $file, $file_i, $i, $gm_pages ) = '';
my ( %kills, %clients_by_hour, %rec, %config, @arr ) = ();

my ( $start_time ) = time;	# Будем мерять время, потому что это круто!

# Константы
my $max_width_graph = 300;
my $max_width_text = 50;

# Читаем файл с конфигом
if( open (FILE, "<logstats.cfg") ) {	# Дальнейшее имеет смысл только если есть файло
 while($str = <FILE>) {
  $str =~ s/\r?\n//g;
  $str =~ s/[\s\t]*\#.+//g;
  ( $name, $val ) = split( /\s*=\s*/, $str );
  if( defined( $name ) ) {
   $name = lc( $name );
   $config{$name} = defined($val)?$val:'';
  }
 }
 close (FILE) || die "Can't close logstats.cfg: $!";
}

($secn,$minn,$hourn,$dayn,$monn,$yearn) = localtime(time);
$monn = $monn+1;
$yearn += 1900 if ( $yearn < 1900 ) ;
$monn = "0$monn" if ($monn<10);
$dayn = "0$dayn" if ($dayn<10);
$hourn = "0$hourn" if ($hourn<10);
$minn = "0$minn" if ($minn<10);
$secn = "0$secn" if ($secn<10);

# Читаем файл с логом
$file = $config{logpath}."sphere$yearn-$monn-$dayn.log";
open( FILE, "$file" ) || die "Can't read file $file: $!";
while( $str = <FILE> ) {
 $str =~ s/\r?\n//g;
 $str =~ /(\d+):(\d+):(([0-9a-f|ERROR|WARNING]+):)?(.+)/;
 ( $rec{hour}, $rec{min}, $rec{id}, $rec{action} ) = ( $1, $2, $4, $5 );
 if ( defined( $rec{action} ) ) {
  if ( $rec{action} =~ /^Client\s(dis)?connected\s\[Total:(\d+)\]/ ) {
   $clients_by_hour{$rec{hour}}{sum} += $2;
   $clients_by_hour{all}{sum} += $2;
   $clients_by_hour{$rec{hour}}{count}++;
   $clients_by_hour{all}{count}++;
   $clients_by_hour{$rec{hour}}{avg} = int $clients_by_hour{$rec{hour}}{sum} / $clients_by_hour{$rec{hour}}{count};
   if( !defined( $clients_by_hour{all}{max} ) || 
 	$clients_by_hour{$rec{hour}}{avg} > $clients_by_hour{all}{max} ) {
    $clients_by_hour{all}{max} = $clients_by_hour{$rec{hour}}{avg};
   }
  }
  if ( $rec{action} =~ /^gm\spage\sfrom/i ) {
   $gm_pages++;
  }
  if ( $rec{action} =~ /^P\'(.+)\'\swas\skilled\sby\s(.+)\.$/ ) {
   $kills{killall}++;
   $kills{killers} = $2;
   if ( $kills{killers} eq 'accident' ) {
    $kills{accident}++;
   } else {
    @arr = split( /,\s/, $kills{killers} );
    $kills{by_p} = 0;
    $kills{by_n} = 0;
    foreach( @arr ) {
     $_ =~ /^([PN])/;
#     print "$rec{action}: $#arr=$_=1:$1=2:$2=\n";
     if( $1 eq 'P' ) {
      $kills{by_p} = 1;
     } else {
      $kills{by_n} = 1;
     }
    }
    if ( $kills{by_p} ) {
     $kills{by_player}++;
    } else {
     $kills{by_npc}++;
    }
   }
  }
 }
}
close( FILE );

# Записываем результаты в HTML
$file = $config{outputpath}."${yearn}${monn}${dayn}.html";
open( FILE, ">$file" ) || die "Can't write file $file: $!";
print FILE "<HtML>\n<Head>\n<Title>Статистика шарда ".$config{shardname}." за ${dayn}.${monn}.${yearn}</Title>\n";
print FILE "<Style>\n";
print FILE "Body	{ font-family: ".$config{fontfamily}."; font-size: ".$config{fontsize}."; }\n";
print FILE "TH		{ font-family: ".$config{fontfamily}."; font-size: ".$config{fontsize}."; }\n";
print FILE "Table.Stat	{ border: 1px double #000000; }\n";
print FILE "</Style>\n";
print FILE "</Head>\n<Body BGColor='".$config{bgcolor}."' TEXT='".$config{textcolor}."' LINK='".$config{linkcolor}."' VLINK='".$config{vlinkcolor}."'>\n";
print FILE "<Center>\n";
print FILE "<H3>Статистика шарда ".$config{shardname}." за ${dayn}.${monn}.${yearn}</H3>\n";
print FILE "<HR>\n";
print FILE "<Table Border='0' CellSpacing='3' CellPadding='2' Class='Stat'>\n";
print FILE "<Tr><Th ColSpan='24'>Количество клиентов по часам</Th></Tr>\n";
print FILE "<Tr><Th ColSpan='24'><Hr Size='1' Color='#000000'></Th></Tr>\n";
print FILE "<Tr>";
print FILE "<Tr VAlign='Bottom'>";
foreach $i ( sort keys %clients_by_hour ) {
 next if ( $i eq 'all' );
 print FILE "<Td align='center'><font size='-3'>$clients_by_hour{$i}{avg}<Br>";
 if ( $clients_by_hour{$i}{count} > 0 ) {
  print FILE "<Img Src='".$config{imagepath}."pdbl_v.gif' Width='10' Height='".(int $clients_by_hour{$i}{avg} / $clients_by_hour{all}{max} * $max_width_graph)."'>";
 } else {
  print FILE "<Img Src='".$config{imagepath}."pdbl_v.gif' Width='10' Height='1'>";
 }
 print FILE "</font></Td>";
}
print FILE "</Tr>\n";
print FILE "<Tr>";
foreach $i ( sort keys %clients_by_hour ) {
 next if ( $i eq 'all' );
 print FILE "<Td align='center'><font size='-3'>$i</font></Td>";
}
print FILE "</Tr>\n";
print FILE "<Tr><Th ColSpan='24'><Hr Size='1' Color='#000000'></Th></Tr>\n";
print FILE "<Tr><Th ColSpan='24'>Среднее число клиентов за день: ".($clients_by_hour{all}{count}>0?int $clients_by_hour{all}{sum}/$clients_by_hour{all}{count}:0).", всего логинов/логаутов: $clients_by_hour{all}{count}</Th></Tr>\n";
print FILE "</Table>\n<Br>\n";
print FILE "</Center>\n";
print FILE "<HR>\n";
print FILE "GM pages отправлено: $gm_pages<Br>\n";
print FILE "Всего смертей: $kills{killall}<Br>\n";
print FILE "&nbsp;&nbsp;&nbsp;&nbsp;Убито другими игроками: $kills{by_player}<Br>\n";
print FILE "&nbsp;&nbsp;&nbsp;&nbsp;Убито NPC: $kills{by_npc}<Br>\n";
print FILE "&nbsp;&nbsp;&nbsp;&nbsp;Несчастных случаев: $kills{accident}<Br>\n";
print FILE "<HR>\n";
print FILE "<P>Отчет сформирован за ".(time-$start_time)." секунд</P>\n";
print FILE "<P Align='Center'><Small>Written by <A HRef='mailto:bonik\@pisem.net'>Bonik Forever</A> (c) 2001</Small></P>\n";
print FILE "</Body>\n</HtML>";
close( FILE );

$file_i = $config{outputpath}."index.html";
open( FILE_IN, ">$file_i" ) || die "Can't write file $file_i: $!";
open( FILE_OUT, "<$file" ) || die "Can't read file $file: $!";
while(<FILE_OUT>) {
 print FILE_IN $_;
}
close( FILE_OUT );
close( FILE_IN );
