
if (lc($^O) eq 'mswin32') {
  $win321 = '';
} else {
  $win321 = './';
}

@exclude = ();
$stats_footer = "";
$stats_header = "";
$statsaverage = 1;

srand;

if (eval "use Time::HiRes", $@) {$notime = 1;}

if (!defined($ARGV[0])) {
  die ("ERROR No argument specified, to run from command line use perl genstats.pl botname");
}

$scriptname = $ARGV[0];

do "$win321$scriptname.conf" or die("ERROR Couldn't load $scriptname.conf: $!");

open (LOGFILE, $logfile) or die("ERROR Couldn't open log file $logfile: $!");

if ($notime) {
  $oldtime = time();
} else {
  $oldtime = Time::HiRes::time();
}

$lines = -1;

NEXTLOOP:while ($logline = <LOGFILE>) {
  chop ($logline);

  ($ctime, $action, $nickname, $text) = split ("\001", $logline);

  foreach (@exclude) {
    if (lc($nickname) eq lc($_)) {
      next NEXTLOOP;
    }
  }

  $lcnick = lc($nickname);

  if (!exists($stats{$lcnick}->{nick})) {
    $stats{$lcnick}->{nick} = $nickname;
  }

  $lines++;

  $t = $lines;

  $textarray[$t] = $text;

  if ($action & 8) {
    $action &= ~8;
    $stats{$lcnick}->{sweareg}[$stats{$lcnick}->{swear}++] = \$textarray[$t];
  }

  if ($action == 0) {
    $stats{$lcnick}->{line}[$stats{$lcnick}->{lines}++] = \$textarray[$t];
  } elsif ($action == 1) {
    $stats{$lcnick}->{actionline}[$stats{$lcnick}->{action}++] = \$textarray[$t];
  } elsif ($action == 2) {
    $stats{$lcnick}->{bitchline}[$stats{$lcnick}->{bitchcmds}++] = \$textarray[$t];
    $stats{$lcnick}->{line}[$stats{$lcnick}->{lines}++] = \$textarray[$t];
  } elsif ($action == 3) {
    $stats{$lcnick}->{quest}[$stats{$lcnick}->{quests}++] = \$textarray[$t];
    $stats{$lcnick}->{line}[$stats{$lcnick}->{lines}++] = \$textarray[$t];
  } elsif ($action == 4) {
    $stats{$lcnick}->{kicktext}[$stats{$lcnick}->{kicks}++] = \$textarray[$t];
  } elsif ($action == 5) {
    $stats{$lcnick}->{kickedtext}[$stats{$lcnick}->{kicked}++] = \$textarray[$t];
  }
}

if ($statsaverage == 1) {
  foreach $keyname (keys %stats) {
    $averagelines += $stats{$keyname}{lines};
    $averageactions += $stats{$keyname}{action};
  }

  $totallines = $averagelines;

  $averagelines /= scalar keys %stats;
  $averageactions /= scalar keys %stats;

  $averagelines = int($averagelines);
  $averageactions = int($averageactions);

  #if lines less than avg/2, delete

  foreach $keyname (keys %stats) {
    if ($stats{$keyname}{lines} < $averagelines) {
      delete $stats{$keyname};
    }
  }
}

foreach $keyname (keys %stats) {
  if (defined($stats{$keyname}->{swear})) {
    $swearlist[$#swearlist+1] = "$stats{$keyname}->{swear}\001$keyname";
  }

  if (defined($stats{$keyname}->{lines})) {
    $lineslist[$#lineslist+1] = "$stats{$keyname}->{lines}\001$keyname";
  }

  if (defined($stats{$keyname}->{action})) {
    $actionslist[$#actionslist+1] = "$stats{$keyname}->{action}\001$keyname";
  }

  if (defined($stats{$keyname}->{quests})) {
    $questslist[$#questslist+1] = "$stats{$keyname}->{quests}\001$keyname";
  }

  if (defined($stats{$keyname}->{bitchcmds})) {
    $bitchlist[$#bitchlist+1] = "$stats{$keyname}->{bitchcmds}\001$keyname";
  }

  if (defined($stats{$keyname}->{kicks})) {
    $kicklist[$#kicklist+1] = "$stats{$keyname}->{kicks}\001$keyname";
  }

  if (defined($stats{$keyname}->{kicked})) {
    $kickedlist[$#kickedlist+1] = "$stats{$keyname}->{kicked}\001$keyname";
  }
}

$tlines = $lines;

if ($^O eq 'linux') {
  foreach (`ps u $$ | awk '{print "Peak RAM usage: "\$6 " KBytes ("\$4 "%)"}'`) {
    $pstats = $_;
  }
} else {
  $pstats = 'Visit <a href="http://www.r1ch.net/">www.r1ch.net</a> for more information on bitchbot.';
}

#####################
# WRITE OUT RESULTS #
#####################
open (OUTFILE,">$outfile") or die("ERROR Can't write to $outfile : $!");

################
# HEADERS FILE #
################
print OUTFILE <<Headers;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="Generator" content="bitchbot channel stats module">
  <meta name="Description" content="IRC channel statistics for $channel on $server:$serverport. View the most active people, rudest, most expressive and inquisitive and see who the op abusers and victims are! Generated by $botname, a bitchbot IRC bot by R1CH.">
  <TITLE>$channel channel stats</TITLE>
  <style type="text/css">
    body, td { font-family: Verdana, serif; font-size: small; color: #FFFFFF }
    body { background-color: #000000 }
    table, tr, td { border-color: #000000 }
    table { margin-left: 60px }
  </style>
</HEAD>
<BODY bgcolor="000000" text="#FFFFFF" link="#FF0000" vlink="#800000" alink="#FFFF00">$stats_header
<CENTER><H1>Channel statistics for $channel provided by $botname!</H1></CENTER>
Headers

print OUTFILE <<Headers;
<H1>Most lines</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#CC0000">
  <TD>
    <B>#</B>
  <TD>
    <B>Lines</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random quote</B>
</TR>
Headers

#############
# SORT LIST #
#############
@lineslist = sort {numeric($a,$b)} @lineslist;


##################
# MOST LINES CNT #
##################
$ndone = 0;
foreach $logline (@lineslist) {
  if ($ndone++ == $maxstats) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{line};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  $i++;

  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#776666">$i
<TD BGCOLOR="#665555">$lines
<TD BGCOLOR="#554444">$stats{$keyname}{nick}
<TD BGCOLOR="#443333">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";

###############
# SWEAR STATS #
###############
$i = 0;

#############
# SORT LIST #
#############
@swearlist = sort {numeric($a,$b)} @swearlist;

print OUTFILE <<Headers;
<H1>Rudest people</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#00CC00">
  <TD>
    <B>#</B>
  <TD>
    <B>Lines</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random quote</B>
</TR>
Headers

$ndone = 0;
foreach $logline (@swearlist) {
  if ($ndone++ == $maxstats) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{sweareg};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  if (length($word) > 110) {
    $word = substr ($word, 0, 110) . '...';
  }

  $i++;


  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#667766">$i
<TD BGCOLOR="#556655">$lines
<TD BGCOLOR="#445544">$stats{$keyname}{nick}
<TD BGCOLOR="#334433">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";



################
# ACTION STATS #
################
$i = 0;

#############
# SORT LIST #
#############
@actionslist = sort {numeric($a,$b)} @actionslist;

print OUTFILE <<Headers;
<H1>Most expressive</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#0000CC">
  <TD>
    <B>#</B>
  <TD>
    <B>Actions</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random action</B>
</TR>
Headers

$ndone = 0;
foreach $logline (@actionslist) {
  if ($ndone++ == $maxstats) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{actionline};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  if (length($word) > 110) {
    $word = substr ($word, 0, 110) . '...';
  }

  $i++;

  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#666677">$i
<TD BGCOLOR="#555566">$lines
<TD BGCOLOR="#444455">$stats{$keyname}{nick}
<TD BGCOLOR="#333344">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";

###############
# QUERY STATS #
###############
$i = 0;

#############
# SORT LIST #
#############
@questslist = sort {numeric($a,$b)} @questslist;

print OUTFILE <<Headers;
<H1>Most inquisitive</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#00CCCC">
  <TD>
    <B>#</B>
  <TD>
    <B>Qs</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random question</B>
</TR>
Headers

$ndone = 0;
foreach $logline (@questslist) {
  if ($ndone++ == $maxstats) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{quest};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  if (length($word) > 110) {
    $word = substr ($word, 0, 110) . '...';
  }

  $i++;

  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#667777">$i
<TD BGCOLOR="#556666">$lines
<TD BGCOLOR="#445555">$stats{$keyname}{nick}
<TD BGCOLOR="#334444">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";


################
#   BOT USAGE  #
################
$i = 0;

#############
# SORT LIST #
#############
@bitchlist = sort {numeric($a,$b)} @bitchlist;

print OUTFILE <<Headers;
<H1>Top $botname users</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#CC00CC">
  <TD>
    <B>#</B>
  <TD>
    <B>Uses</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random command</B>
</TR>
Headers

$ndone = 0;
foreach $logline (@bitchlist) {
  if ($ndone++ == $maxstats) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{bitchline};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  if (length($word) > 110) {
    $word = substr ($word, 0, 110) . '...';
  }

  $i++;
  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#776677">$i
<TD BGCOLOR="#665566">$lines
<TD BGCOLOR="#554455">$stats{$keyname}{nick}
<TD BGCOLOR="#443344">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";

################
#   MOST KICKS #
################
$i = 0;

#############
# SORT LIST #
#############
@kicklist = sort {numeric($a,$b)} @kicklist;

print OUTFILE <<Headers;
<H1>Top 5 $channel op abusers</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#CCCC00">
  <TD>
    <B>#</B>
  <TD>
    <B>Kicks</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random kick</B>
</TR>
Headers
print " we have " . scalar @kicklist . "entries\n";
$ndone = 0;
foreach $logline (@kicklist) {
  if ($ndone++ == 5) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);
  @w = $stats{$keyname}{kicktext};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
print " found $word\n ( " . scalar @w . "\n)";
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  $i++;
  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#777766">$i
<TD BGCOLOR="#666655">$lines
<TD BGCOLOR="#555544">$stats{$keyname}{nick}
<TD BGCOLOR="#444433">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";

#################
#   MOST KICKED #
#################
$i = 0;

#############
# SORT LIST #
#############
@kickedlist = sort {numeric($a,$b)} @kickedlist;

print OUTFILE <<Headers;
<H1>Top 5 $channel victims</H1>
<TABLE BGCOLOR="555555" BORDER=1 ALIGN="center">
<TR BGCOLOR="#999999">
  <TD>
    <B>#</B>
  <TD>
    <B>Kicked</B>
  <TD>
    <B>Nickname</B>
  <TD>
    <B>Random kick</B>
</TR>
Headers

$ndone = 0;
foreach $logline (@kickedlist) {
  if ($ndone++ == 5) {
    last;
  }

  ($lines,$keyname) = split(/\001/,$logline);

  @w = $stats{$keyname}{kickedtext};
  @w = @{$w[0]};

  $timeout = 0;
  $word = '';

  while (length($word) < 25) {
    $word = ${$w[int rand(@w)]};
    $timeout++;
    if ($timeout == 25) {
      $word = ${$w[int rand(@w)]};
      last;
    }

    if (length($word) > 110) {
      $word = '';
    }
  }

  $i++;
  print OUTFILE <<END;
<TR>
<TD BGCOLOR="#777777">$i
<TD BGCOLOR="#666666">$lines
<TD BGCOLOR="#555555">$stats{$keyname}{nick}
<TD BGCOLOR="#444444">$word
</TR>
END
}

print OUTFILE "</TABLE>\n";

####################
# PROCESS TIME CNT #
####################
if ($notime) {
  $ctime = time();
} else {
  $ctime = Time::HiRes::time();
}
$upTime = ($ctime-$oldtime);
$upString = "";

$upYears = int($upTime / (60*60*24*365));
if ($upYears > 0) {
	$upString .= $upYears." year";
	$upString .= "s" if ($upYears > 1);
	$upString .=", ";
}
$upTime -= $upYears * 60*60*24*365;

$upWeeks = int($upTime / (60*60*24*7));
if ($upWeeks > 0) {
	$upString .= $upWeeks." week";
	$upString .= "s" if ($upWeeks > 1);
	$upString .=", ";
}
$upTime -= $upWeeks * 60*60*24*7;

$upDays = int($upTime / (60*60*24));
if ($upDays > 0) {
	$upString .= $upDays." day";
	$upString .= "s" if ($upDays > 1);
	$upString .=", ";
}
$upTime -= $upDays * 60*60*24;

$upHours = int($upTime / (60*60));
if ($upHours > 0) {
	$upString .= $upHours." hour";
	$upString .= "s" if ($upHours > 1);
	$upString .=", ";
}
$upTime -= $upHours *60*60;

$upMinutes = int($upTime / 60);
if ($upMinutes > 0) {
	$upString .= $upMinutes." minute";
	$upString .= "s" if ($upMinutes > 1);
	$upString .=", ";
}
$upTime -= $upMinutes * 60;

$upSeconds = $upTime;
$upString .= $upSeconds." second";
$upString .= "s" if ($upSeconds != 1);

if (substr($upString,-2,2) eq ', ') {
  $upString = substr($upString,0,(length($upString)-2));
}

$sizem = (stat($logfile))[7];
$sizem /= (1024*1024);
if (length($sizem) > 5) {
  $sizem = substr($sizem,0,5);
}

if ($upString eq '') {
  $upString = "0 seconds";
}

##################
# CLOSE HEADERS! #
##################
print OUTFILE $stats_footer;
print OUTFILE <<Footers;

<BR>
<HR>
There were a total of $tlines lines parsed in this analysis. The log file is currently ${sizem}mb. Want cool stats like this for you channel? Then you need a <a href=\"http://www.r1ch.net/projects/bitchbot/\">bitchbot</a> today.
<HR>
<P><BR>
<a href="http://www.r1ch.net/projects/bitchbot/"><img border=0 src="http://www.r1ch.net/projects/bitchbot/images/bbot.png" width=127 height=10 alt="bitchbot"></a><BR>
<FONT SIZE=1 COLOR="#AAAAAA"><I>Made with Ilog 1.2/perl by <a href="http://www.r1ch.net/">r1ch</a>. Running time: ${upString}. $pstats</I></FONT>
</BODY>
</HTML>

Footers

close (OUTFILE) or die("ERROR Can't close $outfile! $!");
close (LOGFILE) or die("ERROR Can't close $logfile! $!");

print "OK Stats generation complete!\n";

####################
# SORT NUMERICALLY #
####################
sub numeric {
  if ($a > $b) {
    return -1;
  } elsif ($a == $b) {
    return 0;
  } elsif ($a < $b) {
    return 1;
  }
}
