#!/afs/athena/contrib/perl/p

$kindex = '';
$dindex = '';


while(<>){
    $body = 1 if /^$/;
    $header .= $_."\n";
    next unless $body;

    $lines[$ln++]=$_;
}

if($lines[0]=~/[a-z]+:.+/){
    $url = $lines[0];
}
else{
    &error("Error in URL format\nURL must be on first line of message body", $header);
}

if($lines[1]=~/[a-zA-Z]/){
    $title=$lines[1];
}
else{
    &error("Invalid title\nTitle must be on second line and must contain\nan alpha charachter", $header);
}

if($lines[3]=~/[a-zA-Z]/){
    $keywords=$lines[3];
}
else{
    &error("Invalid keywords\nKeywords must be on third line and must contain\nan alpha character", $header);
}

if($lines[4]=~/./){
    &error("Fourth line must be blank\n", $header);
}

$desc=join("\n", @lines[5..$#lines]);

if($desc!~/[a-zA-Z]/){
    &error("Invalid description\nDescription must appear on lines 5 and after\n", $header);
}

$url=~/[a-zA-Z]+:\/\/([^:]+):/;
$site = $1;


$val = &add_entry($url, $title, $site, $keywords, $desc);
&fail("Added index entry number $val for\n$url");

sub add_entry{
    local($url, $title, $site, $keys, $desc)= @_;
    
    $ll = `tail -1 $kindex`;
    ($n, $garbage)=split(';', $ll);
    $n++;

    open(KIN, ">>$kindex") || &fail("Can't open kindex");
    open(DIN, ">>$dindex")|| &fail("Can't open dindex");

    print(KIN, "$n;$keys\n");
    print(DIN, "$n$url$title$site$desc\n");

    close(KIN); close(DIN);
    
    $n;
    
}

sub fail {
    local($message) = @_;

    &zme($message);

    exit(0);
}


sub zme {
        local($message) = @_;
        open (ZME, "|zwrite -n -q -d -s 'WWW' -c www-log");
        print(ZME $message);
        close(ZME);
}

sub error {
    local($error, $h) = @_;
    local($from);

    $h =~/From: (.+)/i;
    $from = $1;

    exit(0) if (!$from);

    open(MAIL, "|/bin/mail -s 'WWW Index Submission' $from");

    print(MAIL "Your submission to the WWW index was not accepted.\n");
    print(MAIL $error);
    print(MAIL "\n\nThanks very much, please try again. The format for\n");
    print(MAIL "messages is\n");
    print(MAIL "----------first line of message follows-------\n");
    print(MAIL "url://your/path\n");
    print(MAIL "Title here\n");
    print(MAIL "space seperated keyword list\n");
    print(MAIL "\n");
    print(MAIL "Description of document which may be\n");
    print(MAIL "more than one line\n");
    print(MAIL "---------preceding line is last line of message-----\n");
    print(MAIL "\n\nThanks!\n");
    close(MAIL);

    &fail("Rejected mail from $from\n");
}
