#!/usr/local/bin/perl5 -s
#
# This file is part of SnarfNews
# Copyright (C) 1991,1992,1993,1994,1995,1996 Alec Muffett
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

require "snarf.pl";

$usage = "ihaveart [-debug] [-genid] hostname[:port]\n";
$host = shift || die $usage;

# dig out the msgid
$msgid = undef;

# read/check header for validity
while (<>)
{
    $debug && warn "| $_";      # debug info
    s/^\./../o;                 # have to do this here, shouldnt be needed

    if (/^\s+/o && ($#header >= 0))
    {
	$header[$#header] .= $_;
    } else
    {
	push(@header, $_);
    }

    unless (defined($msgid))
    {
	if ($header[$#header] =~ /^message-id:\s+(<\S+>)/oi)
	{
	    $msgid = $1;
	}
    }

    last if /^\s*$/o;           # break off header on blank line
}

if ($#header <= 0)
{
    warn "ihaveart: empty header\n" if ($debug);
    exit 0;
}

# if we are asked to generate a message-id
if ($genid)
{
    unless (defined($msgid))
    {
	$foo = sprintf("snarf%d.%d", time, $$);
	$bar = $ENV{"SNARFHOST"} ||
	    die "ihaveart: require SNARFHOST variable\n";
	chomp($bar);
	$msgid = "<$foo\@$bar>";
	push(@header, "Message-Id: $msgid\n");
    }
}
else
{
    die "ihaveart: can't find message-id\n" unless (defined($msgid));
}

# setup connection
unless (OpenNNTP($host))
{
    die "ihaveart: cannot open connection to $host\n";
}

# read a line to see if we got a good connection.
if (($_ = &RecvNNTP(0)) !~ /^200/o)
{
    die "ihaveart: service unavailable: $_";
}

# send a IHAVE command and see what happens
&SendNNTP("IHAVE $msgid\n");

if (($_ = &RecvNNTP(0)) !~ /^335/o)
{
    die "ihaveart: server didn't like IHAVE command: $_";
}

# header of posting
foreach (@header)
{
    &SendNNTP($_);
}

# body of posting
while (<>)
{
    s/^\./../o;
    &SendNNTP($_);
}

# end of posting
&SendNNTP(".\n");

if (($_ = &RecvNNTP(0)) !~ /^235/o)
{
    die "ihaveart: server didn't like end of posting: $_";
}

&SendNNTP("QUIT\n");

if (($_ = &RecvNNTP(0)) !~ /^205/o)
{
    warn "ihaveart: server didn't like QUIT command: $_";
}

exit 0;
