require "flush.pl";

#
# Directories 
#

$ENV{SERVER_JOBS}      = "$ENV{SERVER_VAR}/jobs";
$ENV{SERVER_LOGS}      = "$ENV{SERVER_VAR}/logs";
$ENV{SERVER_DATABASES} = "$ENV{SERVER_VAR}/databases";

#
# Other
#

$ENV{SERVER_VERBOSE}       = 1;
$ENV{SERVER_SPOOL}         = "$ENV{SERVER_VAR}/spool";
$ENV{MAIL_FOLDER}          = "$ENV{HOME}/Mail";
$ENV{SERVER_SIGNATURE}     = "Thanks - $ENV{SERVER_NAME} Staff";

#
# Process command line arguments
#

foreach (@ARGV) {
  $args .= $_;
}
@ARGS = split(/\-/, $args);
shift(@ARGS);
foreach (@ARGS) {
  if (/^clean$/) {
    $CLEAN = 1;
  } elsif (/^v$/) {
    $ENV{SERVER_VERBOSE} = 1;
  } else {
    print "$0: unknown option $_\n";
    print "$0: usage $0 [-clean] [-v]\n";
    exit(1);
  }
}

#
# Tidy up a bit
#
 
if ($CLEAN) {
  if ($ENV{SERVER_VERBOSE}) {
    print "removing old logs in $ENV{SERVER_LOGS}...\n";
  }
  system("rm -f $ENV{SERVER_LOGS}/scheduler");
  system("rm -f $ENV{SERVER_LOGS}/socket");
  system("rm -f $ENV{SERVER_LOGS}/receiver");
  system("rm -f $ENV{SERVER_LOGS}/queues");
  system("rm -f $ENV{SERVER_LOGS}/cleaner");
  system("rm -f $ENV{SERVER_LOGS}/checker");
}

system("rm -f $ENV{SERVER_VAR}/tmp/*");

#
# Start Server
#

$command = "exec $ENV{SERVER_PERL} $ENV{SERVER_BIN}/receiver.pl >> $ENV{SERVER_LOGS}/receiver 2>&1";
if ($ENV{SERVER_VERBOSE}) {
  print "starting $ENV{SERVER_NAME} receiver...\n"; 
}
if (!fork()) {
  system("echo $$ > $ENV{SERVER_VAR}/proc/receiver.pid");
  exec($command);
}

#
# Start Scheduler 
#

$command = "exec $ENV{SERVER_PERL} $ENV{SERVER_BIN}/scheduler.pl >> $ENV{SERVER_LOGS}/scheduler 2>&1";
if ($ENV{SERVER_VERBOSE}) {
  print "starting $ENV{SERVER_NAME} scheduler...\n"; 
}
if (!fork()) {
  system("echo $$ > $ENV{SERVER_VAR}/proc/scheduler.pid");
  exec($command);
}

#
# Start Socket Server
#

$command = "exec $ENV{SERVER_PERL} $ENV{SERVER_BIN}/socket-server.pl $ENV{SERVER_PORT} >> $ENV{SERVER_LOGS}/socket 2>&1";
if ($ENV{SERVER_VERBOSE}) {
  print "starting $ENV{SERVER_NAME} socket-server...\n"; 
}
if (!fork()) {
  system("echo $$ > $ENV{SERVER_VAR}/proc/socket-server.pid");
  exec($command);
}

