#!/usr/local/bin/perl

# dochk Version 1.0 - By Chris Candreva
# Stardate 0814.95
# Script to automaticly process checkgroups messages
#
# 1) strip mail header off
# 2) feed to docheckgroups
# 3) run ctlinnd commands
# 4) add/remove lines in newsgroups file.

$ctlinnd = '/usr/local/news/bin/ctlinnd';

$newsgroups = '/usr/local/news/newsgroups';
$newsgroups1 = $newsgroups.'.tmp';

unless ($ARGV[0]) {
	print "Must supply an input file.\n";
	exit 1;
}

$chkfile = $ARGV[0];
$chkfile1 = $chkfile.'.tmp';
$chkfile2 = $chkfile.'.out';

if ( -f $chkfile1 ) {die "Already processing $chkfile."; }

open (IN,$chkfile) || die "Can't open input file";
open (OUT,">$chkfile1");
while (<IN>) { if (/-EOF-/) { last; } }
print OUT $_;
while (<IN>) {print OUT $_;}
close IN;
close OUT;

chmod 0700, $chkfile1;

system "$chkfile1 > $chkfile2";

open (IN,$chkfile2);
while (<IN>) {
	if (s/^\011//) {
		chop;
		s/^ctlinnd/$ctlinnd/;
		print "$_\n";
		system $_;
	} elsif ( /^\# Remove these lines:/ ) {
		last;
	}
}

# Build table of groups to delete;
while (<IN>) {
	chop;
	if ($_ eq '') {last;}
	s/^#\011//;
	$remove{$_} = '1';
}

open (NG, $newsgroups);
open (NG1, ">$newsgroups1");
while (<NG>) {
	chop;	
	unless ( defined $remove{$_} ) {
		print NG1 "$_\n";
	} else {print "removed $_\n";}
}
close NG;

# Skip to groups to add;
while (<IN>) { if (/\# Add these lines:/) { last; } }

while (<IN>) {
	if ( s/^#   // ) {
		print NG1 $_;
		print "added: $_";
	}
}	

close NG1;

close IN;

unlink $chkfile1;
unlink $chkfile2;

rename($newsgroups1, $newsgroups);
chmod 0664, $newsgroups;
