#!/usr/bin/perl
print "DEBUG $program"; 
($program = $0) =~ s%.*/%%;

$inews = "/usr/bin/inews";
$iopts = "-h";

if ($#ARGV < 0) {
      $newsgroup = "rotty.test";
      # we'll expect the newsgroup line in the body
} elsif ($#ARGV == 0) {
    $newsgroup = $ARGV[0];
} else {
    die "usage: $program [newsgroup]\n";
}

  # in case inews dumps core or something crazy
$SIG{'PIPE'} = "plumber";
sub plumber { die "$program: \"$inews\" died prematurely!\n"; }

  open (INEWS, "| $inews $iopts") ||
    die "$program: can't run $inews\n";

  # header munging loop
while (<STDIN>) {
    last if /^$/;

     # transform real from: line back to icky style
    s/^From:\s+(.*) <(.*)>/From: $2 ($1)/;

    s/Message-Id/Message-ID/;

     # transform from_ line to path header; also works locally
     s/^From\s+(\S+)@(\S+).*/Path: $2!$1/
	 || s/^From\s+(\S+)[^@]*$/Path: $1\n/;

     print INEWS
  #       if /^(Date|From|Subject|Path|Newsgroups|Organization|Message-ID):/i;
	 if /^(Date|From|Subject|Path|Newsgroups|Message-ID):/i;
    $saw_subject |= ( $+ eq 'Subject' );

    $saw_msgid |= ( $+ eq 'Message-ID' );

  #   $saw_newsgroup |= ( $+ eq 'Newsgroups' );
}

  warn "$program: didn't expect newsgroup in both headers and ARGV\n"
    if $newsgroup && $saw_newsgroup;

  die "$program: didn't get newsgroup from either headers or ARGV\n"
    unless $newsgroup || $saw_newsgroup;

($sec,$min,$hour,$mday,$mon,$year)=localtime(time);
$madeupid = "\<m2n$year$mon$mday.$hour$min$sec.$$\@ep.sci.hokudai.ac.jp\>";

printf INEWS "Newsgroups: %s\n", $newsgroup if $newsgroup;
print  INEWS "Followup-To: rotty.comp\n" if ($newsgroup eq 'rotty.epnetfan');
print  INEWS "Subject: Untitled\n" unless $saw_subject;
printf INEWS "Message-ID: %s\n", $madeupid unless $saw_msgid;
print  INEWS "Organisation: Dept. Earth and Planetary Sciences,",
	"\tHokkaido University (mail-to-news gateway)\n";
print  INEWS "\n";

print INEWS while <STDIN>;   # gobble rest of message

close INEWS;
exit $?;
