#!/usr/bin/perl

# Josh's cheezyhack help-snarfer.
# please don't hurt me.

use IO::Socket;
use IO::File;
use strict;
alarm(120);

my $SERVER = "rpi.lily.org";
my $PORT = 8888; # (7777 is blocked from here, so I have to use devcore instead)

my @toplevel = qw(help);

my $topic;
foreach $topic (@toplevel) {
    get_help($topic);
}
exit(0);

my %got;
sub get_help {
    my ($topic) = @_;

    return if $got{$topic};

    my $sock = IO::Socket::INET->new(PeerAddr => $SERVER,
				     PeerPort => $PORT,
				     Proto    => 'tcp') || die "Error Connecting to $SERVER:$PORT: $!\n";
    $sock->autoflush(1);
    
    my $helpcmd = "help $topic"; $helpcmd =~ s/\///g;
    print "Sending \"$helpcmd\"\n";
    print $sock "$helpcmd\n";    

    my @result = <$sock>;
    $got{$topic} = 1;

    my @topics = write_help($topic, \@result);    
    foreach (@topics) {
	get_help($_);
    }
}

sub write_help {
    my ($topic,$text) = @_;

    my $file = "$topic.html" ;  $file =~ s/\///g;
    my $fh = new IO::File(">$file") || die "Can't open $file: $!\n";
    print $fh "<pre>\n";
    my $show = 0;
    my %found;
    foreach (@$text) {
	s/\</&lt;/g;
	s/\>/&gt;/g;

	if (/login:/) { s/login: //; $show = 1; }
	last if (/\*\*\* Disconnected \*\*\*/);
	next unless $show;
       
	my $line = $_;
	while ($line =~ /(\/[a-z0-9]+)(\s*\S*)/) {
	    my $match = $1; my $cmd = $1;
	    if ($cmd eq "/help") { $match = "$1$2"; $cmd = $2; }
	    $match =~ s/\).*//g;
	    $cmd =~ s/\).*//g;
	    $cmd =~ s/[^a-z0-9\/]*//g;

	    $line =~ s/$match//g;
	    next if ($cmd !~ /\S/);
	    $found{$cmd} = 1;
	}
	
	my $cmd;
	foreach $cmd (keys %found) {
	    my $file = "$cmd.html"; $file =~ s/\///g;
	    if ($cmd =~ /\//) {
		s/$cmd/<a href=\"$file\">$cmd<\/a>/g;
	    } else {
		s/\/help $cmd/\/help <a href=\"$file\">$cmd<\/a>/g;
	    }
	}

	$fh->print($_);
    }

    print $fh "</pre>\n";    

    return (keys %found);
}

