require "flush.pl";
chop($TIME = `date`);

print "receiver: $ENV{SERVER_NAME} restart on $TIME\n"; &flush(STDOUT); 

#
# Set up spooling directories if they don't exist
#

$WEB_SPOOL    = "$ENV{SERVER_SPOOL}/WEB";    
$SOCKET_SPOOL = "$ENV{SERVER_SPOOL}/SOCKET"; 
$KESTREL_SPOOL = "$ENV{SERVER_SPOOL}/KESTREL";
system("mkdir $SOCKET_SPOOL") unless (-d "$SOCKET_SPOOL");
system("mkdir $WEB_SPOOL; chmod a+w $WEB_SPOOL") unless (-d "$WEB_SPOOL");
system("mkdir $KESTREL_SPOOL; chmod a+w $KESTREL_SPOOL") unless (-d "$KESTREL_SPOOL");

#
# create next_serial_number if it doesn't exist
#

system("echo 1 > $ENV{SERVER_VAR}/lib/next_serial_number") unless (-f "$ENV{SERVER_VAR}/lib/next_serial_number");

#
# create next_kestrel_number if it doesn't exist
#

system("echo 1 > $ENV{SERVER_VAR}/lib/next_kestrel_number") unless (-f "$ENV{SERVER_VAR}/lib/next_kestrel_number");

#
# Loop until jobs arrive from one of the interfaces. 
#

for (;;) {
    
    $status = 1;
    $status = system("inc -host $ENV{SERVER_POP_SERVER} -rpop +jobs -silent 2>/dev/null");

CHECK:    while (!(  ($ENV{SERVER_EMAIL_READY} &&  (!($status)) ) || 
	             ($ENV{SERVER_WWW_READY}   && (-f "$WEB_SPOOL/MAIL"))
                 || (-f "$KESTREL_SPOOL/MAIL") || (-f "$SOCKET_SPOOL/MAIL"))) 
    {

	for ($i = 0; $i < 30; $i++)
	{
	    sleep(1);
	    if (($ENV{SERVER_WWW_READY} && (-f "$WEB_SPOOL/MAIL")) || (-f "$KESTREL_SPOOL/MAIL") || (-f "$SOCKET_SPOOL/MAIL"))
	    {
		last CHECK;
	    }
	}
	$status = 1;
	$status = system("inc -host $ENV{SERVER_POP_SERVER} -rpop +jobs -silent 2>/dev/null");   
    }			   
  
  #
  # Jobs are here, so call the initializer.
  #
    if($status == 0)
    {
	system("$^X $ENV{SERVER_BIN}/initializer.pl -mail 2>> $ENV{SERVER_VAR}/logs/receiver");
    } else {
	system("$^X $ENV{SERVER_BIN}/initializer.pl 2>> $ENV{SERVER_VAR}/logs/receiver");
    }
}

sub fsleep {
    select(undef, undef, undef, $_[0]);
}


