# hack to make a colored html version of irssi logs.
# 
# Published at http://barfooze.de/stuff/irssi/color_logs.pl
#
# Please see the LICENSE file for copyright information

use warnings;
use HTML::Entities;

# Source: http://www.perlmonks.org/?node_id=441359
sub getColor {
    my $index = shift; # Numerical index (integer from 0 to .. +.)
    my @color; # Color components

    my @hue_matrix = (
        #
        #   R    G    B   Component to modify(0=R, 1=G, 2=B)
        #   |    |    |    |
        #   V    V    V    V    Add or subtract the offset
        #                       |     from (r,g,b) triplet
        #                       V
        [ 255,   0,   0,   2,   1 ],    # Sector 1   R   -> R+B
        [ 255,   0, 255,   0,  -1 ],    # Sector 2   R+B -> B
        [   0,   0, 255,   1,   1 ],    # ...        B   -> Cyan
        [   0, 255, 255,   2,  -1 ],    # ...        Cyan-> G
        [   0, 255,   0,   0,   1 ],    # ...        ...
        [ 255, 255,   0,   1,  -1 ],
        [ 255,   0,   0,   2,   1 ]
    );

    # Select a "spectrum sector", according to my hue matrix
    my $sector = $hue_matrix[ int($index / 42) % @hue_matrix ];

    # Calculate an offset to be applied to starting color
    my $offset = ($index % 42) * 6;

    @color = @$sector[0..2];

    # Modify selected component to generate a "continuous gradient" 
    $color[$sector->[3]] += ($sector->[4] > 0 ? $offset : -$offset);

    return(@color);
}
 
my $n = 0;
my $factor = 10;
my $colors = {};
print '<body style="background: #111; color: white">';
print "<pre>";
while (<>) {
	if(/(\d{2}:\d{2}) ([^[:alpha:]]+)([[:alpha:]][[:alnum:]~_^`-]+)([\W]*) (.*)/){
		my ($ts, $prenick, $nick, $postnick, $txt) = ($1,$2,$3,$4,$5);
		$colors->{$nick} ||= $n++;
		
		next if $prenick eq "*** " or $prenick eq "-!- "; # strange.theme or default irssi theme. add yours if need be

		if ($prenick =~ /^ ?\*/) { # /me
		printf('%s * <span style="color: #%02x%02x%02x">%s</span> %s%s',
			$ts, getColor($colors->{$nick} * $factor),
			 $nick, encode_entities($txt),"\r\n");
		} else { # generic msg
		printf('%s &lt;<span style="color: #%02x%02x%02x">%s</span>&gt; %s%s',
			$ts, getColor($colors->{$nick} * $factor),
			 $nick, encode_entities($txt),"\r\n");
		}
	}
		
}
print "</pre></body>";
