#!/tools/contrib/bin/perl -w

# test command line:
# export QUERY_STRING='Server=news.europe.nokia.com&Prefix=nokia'; perl listng.pl > temp.html

# bug: the default prefix does not work at all.

# List all newsgroups in a news server starting with some prefix. 
# Defaults are "cnnnews" and any alphanumeric characters. By Claude Bouillin

use CGI;

$mailto = "Claude Bouillin";
$mailaddr = "bouillin\@shire.ntc.nokia.com";
$now = localtime();

my $telnet = "/usr/bin/telnet";
my $port   = "119";
my $grep   = "/usr/site/gnu/bin/grep";
my $cut    = "/usr/site/gnu/bin/cut";
my $tail   = '/usr/site/gnu/bin/tail +6';

$server = "cnnnews.ntc.nokia.com";
$prefix = '^([[:alnum:]]+)\.';
if ($ENV{QUERY_STRING} =~ /Server=([^&]*)\&Prefix=([^&]*)/) {
    $server = $1;
    $prefix = "^" . $2;
}

# print "$prefix\n";
# print "$server\n";

($title, $list) = makelist($server, $prefix);

makepage($title, $list);

sub makelist($$) {
    my ($server, $prefix) = @_;
    
    my $title = "Newsgroups starting with the prefix $prefix on $server ";
    my $cmd = "$telnet $server $port <<EOF | $tail | $grep -E '$prefix' | $cut -d' ' -f1
list
quit
EOF"; 

#    print "$cmd\n";

    # run the $cmd
    my @ngs = `$cmd`;
    chomp @ngs;

    push (@lines, "<ul>");
    my ($ng, $line) = ();

    # embed a tag in each line
    foreach $ng (@ngs) {
	$line = "  <li><a href=\"news://$server/$ng\">$ng</a>";
	push (@lines, $line);
    }
    push (@lines, "</ul>");

    my $list = join "\n", @lines;
    return ($title, $list)
}

sub makepage($$) {
    my ($title, $contents) = @_;

    print "Content-type: text/html\n\n";
    print "<html> <head>\n";
    print "<title>$title</title>\n";
    print "</head>\n";
    print "<body>\n";
    print "<h1>$title</h1>\n\n";

    print "$contents\n\n";

    print "$now";
    print "<hr>\n";
    print "<address>\nThis page is automagically generated.\n";
    print "Mail your remarks to <a href=\"mailto: $mailaddr\">$mailto</a>\n</address>\n";
    print "</body>\n</html>\n";
}


