#!/usr/athena/bin/perl
#
# Accepts NNTP feed, and sends articles as mail to the appropriate address
#
# kolya@MIT.EDU, 05 Jul 1999
#
require '/news/nntp2mail.cf';
$|=1;

print "200 nntp2mail news relay to serve all your relaying needs\r\n";

while(<>) {
 $msg=&trim($_);
 if($msg=~/^mode stream$/i) { print "203 stream along\r\n"; }
 elsif($msg=~/^check (.*)$/i) { print "238 $1\r\n"; }
 elsif($msg=~/^takethis (.*)$/i) {
  $gmsgid=&take_article;
  print "239 $gmsgid\r\n"; }
 elsif($msg=~/^ihave (.*)$/i) {
  print "335 $1\r\n";
  $gmsgid=&take_article;
  print "235 $gmsgid\r\n"; }
 elsif($msg=~/^quit/i) { print "205 bye-bye\r\n"; exit; }
 else { print "500 bzzt\r\n"; }
}

sub take_article {
 $header=1;
 $article="";
 $line="";
 $grouplist=""; @groups=();

 while($line ne ".") {
  $in=<>;
  $line=&trim($in); if($line ne ".") {
   if(substr($line,0,1) eq ".") {
    $article.=substr($line, 1)."\n";
   } else {
    $article.=$line."\n";
   }
  }
  if($header==1) {
   if($line eq "") { $header=0; }
   elsif($line=~/^Message-ID: (.*)$/i) { $msgid=$1; }
   elsif($line=~/^Newsgroups: (.*)$/i) {
    $grouplist=$1;
    @groups=split(/\,/,$grouplist);
   }
  }
 }

 foreach $group (@groups) {
  if($NNTPtoMailGroups{$group} ne "") {
   ($dest, $bounces) = split(/\|/, $NNTPtoMailGroups{$group});
   open(MAILER,"|$NewsToMailPath $dest $dest $bounces $NNTPtoMailHost");
   print MAILER $article;
   close(MAILER);
  }
 }

 return $msgid;
}

sub trim {
 ($str)=@_;
 $last_char=substr($str,length($str)-1,1);
 while(($last_char eq "\n") || ($last_char eq "\r")){
  chop $str; $last_char=substr($str,length($str)-1,1);
 }
 return $str;
}
