#!/usr/bin/perl -w 
# idn registration-script
# wogri@wogri.at 

# Strategy: determine all files to be processed
# Start 3 Exim-Childs with the -odf option to leave them in the foreground!
# Wait for one of them to be finished
# Start the next Exim-Child
# until finished
#

use strict; 

# The SIGCHILD-Signal has to be registered
# $SIG{'CHLD'}=\&childstarvation; 


my $livingchildren=0; 
my $filenr=0; 

sub forknewchild {
	my($fn)=@_; 
	$livingchildren++; 
	print "There are $livingchildren Children alive. - Filename is: $fn\n"; 
	my($pid); 
	$pid=fork();
	if (not defined $pid) {
		print STDERR "Could not fork: $!\n" ;
	}
	unless ($pid) { # Child
		print "Forked a Child!\n"; 
		exec ("/usr/lib/sendmail -odf -v idn-reg\@idn.nic.at < $fn"); 
		# exec ("/usr/lib/sendmail -odf -v wogri\@wogri.at < $fn"); 
		exit(0); 
	}
}

chdir($ARGV[0]) || die "Directory not valid\n"; 
opendir(DIR,".") || die "Could not open dir\n"; 
my @filename=(); 
my $f;
while ($f=readdir(DIR)) {
	unless ($f =~ /^\.+/) {
		@filename=(@filename, $f);
	}
}

# since this works with INODEs, we have to sort the list
@filename = sort(@filename); 

# spawn 3 processe
forknewchild($filename[$filenr++]);
forknewchild($filename[$filenr++]);
forknewchild($filename[$filenr++]);

my $files = @filename; 
print "$files found!\n"; 
while(1) {
	my $pid; 
	$pid=wait(); 
	print "PID $pid died\n"; 
	$livingchildren--; 
	if ($files==$filenr) {
		exit(0); 
	}
	forknewchild($filename[$filenr++]); 
}
