#!/usr/bin/perl -w

#   Copyright (C) 2001-2002 Fernando Gomes
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program 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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
#   USA

use strict;

#Author: Fernando A. P. Gomes
#Email: nocturno@nsk.yi.org

my (%Killer, %Victim, %Games, $type_of_table, %type_of_weapon);
my (%Weapon_Killer, %Weapon_Victim);
my $User;
my %Jogo = ();
my $quake_log = "/home/serv/gameserver/quake3/baseq3/games.log";
my $outputFile = "top";
my $type = "cgi";
my @link;
my $ii = 0;
my ($kr, $kd, $kw);
my $version = "27/11/2000";
my $flag = 1;

#definicao das armas existentes
$type_of_weapon{MOD_ROCKET} = "Rocket Luncher";
$type_of_weapon{MOD_ROCKET_SPLASH} = "Rocket Luncher Splash";
$type_of_weapon{MOD_SHOTGUN} = "Shotgun";
$type_of_weapon{MOD_MACHINEGUN} = "Machine Gun";
$type_of_weapon{MOD_GRENADE} = "Grenade Luncher";
$type_of_weapon{MOD_GRENADE_SPLASH} = "Grenade Luncher Splash";
$type_of_weapon{MOD_PLASMA} = "Plasma Gun";
$type_of_weapon{MOD_PLASMA_SPLASH} = "Plasma Gun Splash";
$type_of_weapon{MOD_RAILGUN} = "Railgun";
$type_of_weapon{MOD_LIGHTNING} = "Lightning Gun";
$type_of_weapon{MOD_BFG} = "The BFG";
$type_of_weapon{MOD_BFG_SPLASH} = "The BFG Splash";
$type_of_weapon{MOD_GAUNTLET} = "Humiliation :))";

#link para a mesma pagina e diferentes tabelas
$link[0] = "Most killed players";
$link[1] = "Players who kill more";
$link[2] = "Weapons more used";

##### Inicio do tratamento de parametros
if (!$ARGV[0]) {
	print "Missing user\n";
	help();
} else {
	$User = $ARGV[0];
}

if ($ARGV[1]) {
        if ($ARGV[1] eq "-l") {
                $quake_log = $ARGV[2];
        } elsif ($ARGV[1] eq "-o") {
                $outputFile = $ARGV[2];
        } elsif ($ARGV[1] eq "-t") {
                $type = $ARGV[2];
        } elsif ($ARGV[1] eq "--help") {
                help();
        } else {
                print "invalid option: $ARGV[1]\n";
                help();
        }
}
if ($ARGV[3]) {
        if ($ARGV[3] eq "-l") {
                $quake_log = $ARGV[4];
        } elsif ($ARGV[3] eq "-o") {
                $outputFile = $ARGV[4];
        } elsif ($ARGV[3] eq "-t") {
                $type = $ARGV[4];
	} elsif ($ARGV[3] eq "--help") {
                help();
	} else {
                print "invalid option: $ARGV[3]\n";
                help();
        }
}
if ($ARGV[5]) {
        if ($ARGV[5] eq "-l") {
                $quake_log = $ARGV[6];
        } elsif ($ARGV[5] eq "-o") {
                $outputFile = $ARGV[6];
        } elsif ($ARGV[5] eq "-t") {
                $type = $ARGV[6];
	} elsif ($ARGV[5] eq "--help") {
                help();
	} else {
                print "invalid option: $ARGV[5]\n";
                help();
        }
}
##### Fim do tratamento de parametros

#print "QUAKE_LOG: $quake_log\n";
open(Q3_LOG, "< $quake_log") or die "open $quake_log: $!";
while(<Q3_LOG>) {
	if ($_ =~/^\s*\d+:\d+\s*Warmup:/) {
		my $ficheiro = 0;
		while ($flag && !($ficheiro =~/^\s*\d+:\d+\s*ShutdownGame:/) && !($ficheiro =~/^\s*\d+:\d+\s*InitiGame:/)) {
			$ficheiro = <Q3_LOG>;
			if (!$ficheiro) {
				$flag = 0;
			}
		}
	} elsif ($_ =~/^\s*\d+:\d+\s*Kill/) {

		$_ =~/\s*\d+:\d+\s*Kill: \d+ \d+ \d+: ([\§\.\^\s\<\>\d\w\[\]]+) killed ([\§\.\^\s\<\>\d\w\[\]]+) by (.+)/; 
		$kr = $1;
		$kd = $2;
		$kw = $3;
		$kr =~ s/\^\d//g;
		$kd =~ s/\^\d//g;
		chomp($kw);
		if ($kr eq "<world>") {
			$kr = "WORLD";
		}
		if ($kr eq $User) {
			$Killer{$kd}++;
			$Weapon_Killer{$kd}{$kw}++;
		}
		if ($kd eq $User) {
			$Victim{$kr}++;
			$Weapon_Victim{$kr}{$kw}++;
		}
	} elsif ($_ =~/^\s*\d+:\d+\s*InitGame:/) {
		%Jogo = ();
	} elsif ($_ =~/\s*\d+:\d+\s*ClientConnect:/) {
		$_ = <Q3_LOG>;
		if ($_ =~/^\s*\d+:\d+\s*ClientUserinfoChanged:/) {
			$_ =~/\s*\d+:\d+\s*ClientUserinfoChanged: \d+ n\\([\§\.\^\s\<\>\d\w\[\]]+)/; 
			$kr = $1;
			$kr =~ s/\^\d//g;
			if (!$Jogo{$kr} && $kr eq $User) {
				$Games{$kr}++;
				$Jogo{$kr} = 1;
                                if (!$Killer{$kr}) {
                                        $Killer{$kr} = 0;
                                }
                                if (!$Victim{$kr}) {
                                        $Victim{$kr} = 0;
                                }
			}
		}
	} elsif ($_ =~/^\s*\d+:\d+\s*Exit:/) {
	}
}
close(Q3_LOG);

if ($type eq "cgi") {
	print "Content-type: text/html\n\n";
	init_cgi();
	begin_table_cgi();
		$type_of_table = "Most killed players";
		write_results_cgi_killer();
		$ii++;
	end_table_cgi();
	begin_table_cgi();
		$type_of_table = "Players who kill more";
		write_results_cgi_victim();
		$ii++;
	end_table_cgi();
	begin_table_cgi();
		$type_of_table = "Weapons more used";
		write_results_cgi_weapon();
		$ii++;
	end_table_cgi();
	close_cgi();
}

#####################
######## SUBS #######
#####################


########################
#### ESCREVE EM CGI
########################

#inicia o formato html
sub init_cgi {

#indica onde foi criado o log
my $generated_host = `uname -n`;
my $hora_analize = localtime;
my $t;

print <<__HTML__;
<HTML>
 <HEAD>
        <TITLE>QUAKE III Logs Analize - Player</TITLE>
	<LINK REV=MADE HREF="mailto:nocturno\@nsk.yi.org">
	<META NAME="copyright" CONTENT="(c) 2000 Group NSK">
 </HEAD>
 <BODY BGCOLOR="#000000" TEXT="#E8E8E8" LINK="#0000FF" VLINK="#FF0000">
	<A NAME="TOP"></A>
	<P ALIGN="center"><img border="0" src="/images/quakearena.gif" lowsrc="/images/quakearenalow.jpg" alt="NSK Quake 3 Arena .. Statistics" width="640" height="130" ></P>
	<BR>
	<BR>
        <H2>Log generated in $generated_host for server nsk.yi.org port 27960</H2>
        <STRONG>Generated at $hora_analize</STRONG><BR>
        <STRONG>If you had news ideas, or find any bugs, please tell us:</STRONG><A HREF=\"mailto:quake3\@nsk.yi.org\"> quake3\@nsk.yi.org</A>
        <CENTER>

	<br>	
	<hr>
	<STRONG> THIS SCRIPT IS UNDER CONSTRUCTION </STRONG>
	<hr>
	<br>

	<HR>
	<BR>
__HTML__
	for (my $t = 0; $t <= $#link; $t++) {
		print "\t<A HREF=\"\#$link[$t]\">[$link[$t]]<A>\n";
	}
	print "\t<BR>\n";
	print "\t<BR>\n";
}
 
#termina o formato html
sub close_cgi() {

print <<__HTML__;

	</CENTER>
	<FONT COLOR="#990000" SIZE="1">Version: $version</FONT>
 </BODY>
</HTML>
__HTML__
}

#inicia a formacao de uma tabela
sub begin_table_cgi {

print <<__HTML__;
	<A NAME="$link[$ii]"></A>
        <TABLE WIDTH=700 BORDER=2 CELLSPACING=1 CELLPADDING=1>
        <TR><TH HEIGHT=4></TH></TR>
__HTML__
}

#termina a formacao de uma tabela
sub end_table_cgi {

print <<__HTML__;
        </TABLE>
        <P><SMALL>
		<A HREF="#TOP">[Back to Top]</A>
	</P></SMALL>
	<BR><BR><BR>
__HTML__
}
#escreve os ultimos resultados em html
sub write_results_cgi_killer {
	my @temp = ();
	my $temp = 0;
	my $lugar = 0;

print <<__TABLE__;
                <TR><TH COLSPAN=5 ALIGN=center BGCOLOR=\"RED\">Status for $User - $type_of_table by $User</TH></TR>
                <TR>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>User killed</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Deaths</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Kills</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Must Used Weapon</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Games Played</B></FONT></TH>
      		</TR>
		<TR><TH HEIGHT=4></TH></TR>
__TABLE__

	if ($type_of_table eq "Most killed players"){
		$lugar = 0;
		@temp = sort {$Killer{$b} <=> $Killer{$a}} keys %Killer;
		for (my $h = 0; $h <= $#temp; $h++) {
			$temp = $temp[$h];
			$lugar++;
			$lugar = "$lugarē - ";
			write_aux($temp, $lugar);
		}
	}
}

sub write_results_cgi_victim {
	my @temp = ();
	my $temp = 0;
	my $lugar = 0;

print <<__TABLE__;
                <TR><TH COLSPAN=5 ALIGN=center BGCOLOR=\"RED\">Status for $User - $type_of_table $User</TH></TR>
                <TR>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Killer User</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Deaths</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Kills</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Must Used Weapon</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Games Played</B></FONT></TH>
      		</TR>
		<TR><TH HEIGHT=4></TH></TR>
__TABLE__

	if ($type_of_table eq "Players who kill more") {
		$lugar = 0;
		@temp = sort {$Victim{$b} <=> $Victim{$a}} keys %Victim;
		for (my $h = 0; $h <= $#temp; $h++) {
			$temp = $temp[$h];
			$lugar++;
			$lugar = "$lugarē - ";
			write_aux($temp, $lugar);
		}
	}
}

sub write_aux {
	my $most_used_weapon = 0;
	my $w;
	my $weap = 0;
	my ($temp, $lugar) = @_;

	print "\t\t<TR>\n";
      	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\"><A HREF=\"playerQ3stats.pl\?$temp\">$lugar $temp</A></FONT></TD>\n";
	if ($Victim{$temp}) {
               	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$Victim{$temp}</FONT></TD>\n";
	} else {
        	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">Never killed $User</FONT></TD>\n";
	}
	if ($Killer{$temp}) {
        	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$Killer{$temp}</FONT></TD>\n";
	} else {
               	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">Never killed $temp</FONT></TD>\n";
	}
#	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$Games{$temp}</FONT></TD>\n";
	$most_used_weapon = 0;
	if ($type_of_table eq "Most killed players") {
		foreach $w (keys %{$Weapon_Killer{$temp}}) {
			if ($Weapon_Killer{$temp}{$w} > $most_used_weapon) {
				$most_used_weapon = $Weapon_Killer{$temp}{$w};
				$weap = $w;
			}
		}
	} elsif ($type_of_table eq "Players who kill more") {
		foreach $w (keys %{$Weapon_Victim{$temp}}) {
			if ($Weapon_Victim{$temp}{$w} > $most_used_weapon) {
				$most_used_weapon = $Weapon_Victim{$temp}{$w};
				$weap = $w;
			}
		}
	}
	if ($type_of_weapon{$weap}) {
        	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\"><IMG border=\"0\" SRC=\"/images/weapons/$weap.jpg\" ALT=\"$type_of_weapon{$weap}\"></FONT></TD>\n";
	} else {
        	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\"><IMG border=\"0\" SRC=\"/images/weapons/MOD_UNKNOWN.jpg\" ALT=\"i$weap\"></FONT></TD>\n";
	}
       	print "\t\t</TR>\n";
	print "\t\t<TR>\n";
}

#escreve as armas mais usadas pelo utilizador
sub write_results_cgi_weapon {
	my %temp_killer = ();
	my %temp_victim = ();
	my @temp_killer = ();
	my $temp = 0;
	my $lugar = 0;
	my $weap = 0;
	my $killer_user = 0;
	my $victim_user = 0;

print <<__TABLE__;
		<TR><TH COLSPAN=3 ALIGN=center BGCOLOR=\"RED\">Status for $User - $type_of_table</TH></TR>
                <TR>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Weapon</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Kills</B></FONT></TH>
		<TH WIDTH=380 ALIGN=center><FONT SIZE=\"3\"><B>Deaths</B></FONT></TH>
      		</TR>
		<TR><TH HEIGHT=4></TH></TR>
__TABLE__

	######### Parte que trata das armas do utilizados $User, com que ele matou mais
	foreach $killer_user (keys %Killer) {
		foreach $weap (keys %{$Weapon_Killer{$killer_user}}) {
			if ($temp_killer{$weap}) {
				$temp_killer{$weap} = $temp_killer{$weap} + $Weapon_Killer{$killer_user}{$weap};
			} else {
				$temp_killer{$weap} = $Weapon_Killer{$killer_user}{$weap};
			}
		}
	}

	######### Parte que trata das armas do utilizados $User, com que ele morreu mais
	foreach $victim_user (keys %Victim) {
		foreach $weap (keys %{$Weapon_Victim{$victim_user}}) {
			if ($temp_victim{$weap}) {
				$temp_victim{$weap} = $temp_victim{$weap} + $Weapon_Victim{$victim_user}{$weap};
			} else {
				$temp_victim{$weap} = $Weapon_Victim{$victim_user}{$weap};
			}
		}
	}

	@temp_killer = sort {$temp_killer{$b} <=> $temp_killer{$a}} keys %temp_killer;
	for (my $t = 0; $t <= $#temp_killer; $t++) {
		$weap = $temp_killer[$t];
		if ($type_of_weapon{$weap}) {
       	 		print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\"><IMG border=\"0\" SRC=\"/images/weapons/$weap.jpg\" ALT=\"$type_of_weapon{$weap}\"></FONT></TD>\n";
		} else {
       			print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\"><IMG border=\"0\" SRC=\"/images/weapons/MOD_UNKNOWN.jpg\" ALT=\"$weap\"></FONT></TD>\n";
		}
        	print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$temp_killer{$weap}</FONT></TD>\n";
		if ($temp_victim{$weap}) {
        		print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$temp_victim{$weap}</FONT></TD>\n";
		} else {
        		print "\t\t<TD WIDTH=380 ALIGN=center><FONT SIZE=\"-1\">$User never died by this weapon</FONT></TD>\n";
		}
		print "\t\t</TR>\n";
		print "\t\t<TR>\n";
	}
}

# mostra o help
sub help {
        print "usage: $0 user [-l quake_log] [-o outputFile] [-t type]\n";
        print "types: html text cgi\n";
        exit(0);
}
