#!/usr/bin/perl

# Florian Unglaub 

use strict;
use warnings;

use POSIX ":sys_wait_h";

$SIG{CHLD} = \&handle_child;
$SIG{KILL} = \&handle_kill;

our $chld_received = 1; 
# initialize with 1 so we don't do a infinite
# loop without ever forking the first child
our $childpid;

# Random Map at startup

my %maplist = (
        0 => 'RO-Kaukasus.rom',
        1 => 'RO-Krasnyioktyabr.rom',
        2 => 'RO-Stalingradkessel.rom',
        3 => 'RO-Odessa.rom',
        4 => 'RO-Ogledow.rom',
        5 => 'RO-Basovka.rom',
        );

my $pidfile="~/pids/public.pid";
        
while ()
        {
        if ( $chld_received )
                {
                unless ( $childpid = fork() )
                        {
                        chdir("$ENV{'HOME'}/system");
                        my $map=$maplist{int(rand(6))}; 
                        my $startup_options=
                                "$map -nohomedir -log=~/logs/public.log 
                                 -ini=redorchestra_public.ini 
                                 -XAdminConfigIni=XAdmin_public.ini";
                        exec("./ucc-bin server $startup_options") or die $!;
                        }
                $chld_received = 0;
                }
                system("echo $childpid > $pidfile");
                sleep(); 
        }

sub handle_child
{
        waitpid($childpid, WNOHANG);
        $chld_received = 1;
        unlink $pidfile or warn $!;
}

sub handle_kill
{
        unlink $pidfile or warn $!;
        return;
}