#!/usr/bin/perl
##
##  MetaTIN -- a TIN frontend for better USENET NetNews reading
##  Copyright (c) 1996-1997 Ralf S. Engelschall, All Rights Reserved.
##

use IO::Socket;

sub existsgroup {
    local ($host, $group) = @_;
    local ($NNTP);

    $NNTP = new IO::Socket::INET(
                    'PeerAddr' => $host,
                    'PeerPort' => 'nntp',
                    'Proto'    => 'tcp',
                    'Timeout'  => 120 );
    $NNTP->autoflush(1);
    $NNTP->getline(); # greating
    $NNTP->print("mode reader\r\n");
    $NNTP->getline(); # greating
    $NNTP->print("group $group\r\n");
    $rc = $NNTP->getline(); # greating
    $rc =~ m|^(\d+) .+|;
    $rc = $1;
    $NNTP->print("quit\r\n");
    $NNTP->close();
    return ($rc == 211 ? 1 : 0);
}

#   the files we operate on
$newsrc     = "$ENV{'HOME'}/.mtinrc";
$newsrcwork = "$ENV{'HOME'}/.newsrc";

#   function to get the topics out of the annotated newsrc
sub NEWSRC_GetTopics {
    local (%NewsgroupTopic) = ();

    $cnt = 1;
    open(FP, "<", "$newsrc");
    while (<FP>) {
        next if m|^[ \t]*#.*$|;
        next if m|^[ \t]*$|;
        if (m|^%%T[ \t]+(.*)$|) {
            $topic_tag = $1;
            $topic_name = "";
            $newsgroups_sub = 0;
            $newsgroups_unsub = 0;
            next;
        }
        if (m|^%%N[ \t]+(.*)$|) {
            $topic_name = $1;
            next;
        }
        if (m|^[a-zA-Z0-9-.]+!.*$|) {
            $newsgroups_unsub++;
            next;
        }
        if (m|^[a-zA-Z0-9-.]+:.*$|) {
            $newsgroups_sub++;
            next;
        }
        if (m|^%%E[ \t]*$|) {
            $key = sprintf("%02d-%s", $cnt, $topic_tag);
            $NewsgroupTopic{$key} = "$topic_name%%$newsgroups_sub%%$newsgroups_unsub";
            $cnt++;
        }
    }
    close(FP);
    return (%NewsgroupTopic);
}

sub NEWSRC_GetTopicPart {
    local($tag) = @_[0];
    local($buffer);
    local($save);

    open(FP, "<", "$newsrc");
    $save = 0;
    while (<FP>) {
        next if m|^[ \t]*#.*$|;
        next if m|^[ \t]*$|;
        if (m|^%%T[ \t]+(.+)[ \t]*$|) {
            if ("$1" eq "$tag") {
                $save = 1;
            }
        }
        if (m|^%%E.*$|) {
            $save = 0;
        }
        if ($save) {
            next if m|^%%.*|;
            $buffer .= $_;
        }
    }
    close(FP);
    return($buffer);
}

sub NEWSRC_SetTopicPart {
    local($tag, $buffer) = @_;
    local($save);

    rename("$newsrc", "$newsrc.bak");
    open(FPI, "<", "$newsrc.bak");
    open(FPO, ">", "$newsrc");
    $set = 0;
    $ignore = 0;
    while (<FPI>) {
        if (m|^%%N.*$|) {
            print FPO $_;
            next;
        }
        if (m|^%%T[ \t]+(.+)[ \t]*$|) {
            if ("$1" eq "$tag") {
                $set = 1;
                $ignore = 0;
                print FPO $_;
                next;
            }
        }
        if (m|^%%E.*$|) {
            $set = 0;
            $ignore = 0;
            print FPO $_;
            next;
        }
        if ($set) {
            if ($ignore == 0) {
                print FPO "$buffer";
                $ignore = 1;
            }
        }
        else {
            print FPO $_;
        }
    }
    close(FPI);
    close(FPO);
}


%NewsgroupTopic = NEWSRC_GetTopics();

$clusters = 0;
foreach $key (sort(keys(%NewsgroupTopic))) {
	$clusters++;
}

$itemlist  = "'' ";
$itemlist .= "'Available Clusters: $clusters. News server: $ENV{NNTPSERVER}' ";
$itemlist .= "'' ";
$n = 1;
foreach $key (sort(keys(%NewsgroupTopic))) {
    $NewsgroupTopic{$key} =~ m|^(.+)%%(.+)%%(.+)$|;
    ($name, $countsub, $countunsub) = ($1, $2, $3);
    $key =~ s|^\d+-||;
    $arg = sprintf("%2d  %3d  %-15s  %-50s <S:%s>", $n, $countsub, $key, $name, $key);
    $arg =~ s|'|\'\\\'\'|g;
    $itemlist .= "'$arg' ";
    $n++;
}
$itemlist .= "'' ";
$itemlist .= "'_____________________________________________________' ";
$itemlist .= "'' ";
$itemlist .= "'Help: <up>,<down> .......... browse cluster list' ";
$itemlist .= "'      <return>,<right> ..... select cluster (run TIN)' ";
$itemlist .= "'      q,<left> ............. quit' ";

$quit = 0;
$pos = 4;
while ($quit ne 1) {
    #   run the fullscreen menu via iSelect
    $tag = `iselect -p$pos -P -n 'MetaTIN 1.0.0' -t 'USENET Newsgroup Clusters' $itemlist`;
    if ($tag eq '') {
        $quit = 1;
        next;
    }
    $tag =~ s|\n$||;
    $tag =~ m|^(\d+):(.*)|;
    ($pos, $tag) = ($1, $2);

    #   copy topic from .mtinrc to newsrc
    $buffer = NEWSRC_GetTopicPart($tag);
    open(FP, ">", "$newsrcwork");
    print FP $buffer;
    close(FP);

    #   run TIN on the newsrc
    system("clear");
    system("tin -r -q -f $newsrcwork");

    #   copy changed topic back to .mtinrc
    $buffer = "";
    open(FP, "<", "$newsrcwork");
    while (<FP>) {
        #if (m|^([^ \t:!\n]+)|) {
        #   if (not existsgroup("$ENV{'NNTPSERVER'}", "$1")) {
        #       print STDERR "WARNING! group $1 not exists - REMOVED\n";
        #       next;
        #   }
        #}
        $buffer .= $_;
    }
    close(FP);
    NEWSRC_SetTopicPart($tag, $buffer);
}
