#!/usr/local/bin/perl5

# $Id: chkerr,v 1.1 1997/11/23 23:47:22 crosser Exp $
#
# $Log: chkerr,v $
# Revision 1.1  1997/11/23 23:47:22  crosser
# Initial revision
#

# daemon for fido7 "automoderator"
# Copyright (c) 1997 Eugene G. Crosser

$LIBDIR="/usr/local/lib/fido7";
$LOGDIR="/var/fido7/log";
$ERRLOG="chkerr";
$PID="chkerr";

unshift(@INC,$LIBDIR);
chdir($LOGDIR);
open(STDERR,">>".$ERRLOG) || die "cannot open $errlog: $!";
print STDERR time," starting\n";

require "config.pl";
require "rfc822.pl";
require "talkuser.pl";

%count;

&lockme || die "cannot lock daemon";

while (1) {
	$total=0;
	foreach $mode('e') {
		$count{$mode}=0;
		unless (chdir($SPOOL.'/'.$mode)) {
			print STDERR time," chdir \"$SPOOL/$mode\": $!\n";
			next;
		}
		unless (opendir(DIR,'.')) {
			print STDERR time," opendir \"$SPOOL/$mode\": $!\n";
			next;
		}
		while ($de=readdir(DIR)) {
			next if ($de=~/^\./);
			next if ($de=~/core/);
			next if ($de=~/^run/);
			next if ($de=~/^bad/);
			#unless (rename($de,'run'.$de)) {
				#print STDERR time," reanme \"$SPOOL/$mode/$de\": $!\n";
				#next;
			#}
			#&process($mode,'run'.$de);
			&process($mode,$de);
		}
		closedir(DIR);
	}
	
	if ($total) {
		print STDERR time," processed:";
		foreach $mode('e') {
			print STDERR " $mode:$count{$mode}";
		}
		print STDERR "\n";
	}
	foreach $k(keys %errlist) {
		print "$errlist{$k}\t$k";
	}
	exit(0);
	#sleep($DELAY);
}

###########################################################################

sub process {
	local($mode,$fn)=@_;

	unless (open(IN,"<".$fn)) {
		print STDERR time," open $mode/$fn: $!\n";
		return;
	}
	($sender,@header)=&rfc822parse(IN);
	print STDERR time," process: '$mode' \"$fn\" <$sender>\n";
	if ($mode eq 'e') {
		$catch=0;
		$caught=0;
		while (<IN>) {
			if (/----- The following addresses had delivery problems -----/) {
				$catch=1;
			} elsif (/Content-Type: message\/delivery-status/) {
				$catch=2;
			} elsif ($catch == 1) {
				if (/^\s*$/) {
					$catch=0;
				} else {
					$errlist{$_}++;
					$caught++;
				}
			} elsif ($catch == 2) {
				if (/^Final-Recipient:/) {
					$errlist{$_}++;
					$catch=0;
					$caught++;
				}
			}
		}
	}
	close(IN);

	unlink($fn) if ($caught);

	$count{$mode}++;
	$total++;
}

sub lockme {
	local($theirpid,$i);
	local($pid)=$PID;

	if (open(LF,"<$pid.pid")) {
		$theirpid=<LF>;
		close(LF);
		return 1 if ($theirpid == $$);
	}

	open(LF,">$pid.$$") || die "cannot create $pid.$$: $!";
	print LF "$$\n";
	close(LF);

	for ($i=1;$i<=5;$i++) {
		if (link($pid.'.'.$$,$pid.'.pid')) {
			unlink($pid.'.'.$$);
			return 1;
		}
		if (open(LF,"<$pid.pid")) {
			$theirpid=<LF>;
			close(LF);
			unlink($pid.'.pid') unless (kill 15,$theirpid);
		}
		sleep 2;
	}
	unlink($pid.'.'.$$);
	return 0;
}
