BEGIN {print "mpMUD starting up...\n"; $Quit = 'problem during startup'}
use constant GC_DEBUG => 0;

use 5.004;
use strict;
use vars qw(
  %Config
  $Quit
);
use lib 'engine';
use MCoreTools;
use MObject;
use MObjectDB;
use MIndex;
use MModules;
use MScheduler;
use MConnection;
use MConnection::Telnet; # must be 'use'd here to register its presence
use MBootstrap;
use MHelp;
use MSocials;

### Initialization ############################################################################################

# catch SIGINT to exit nicely
$SIG{'INT'} = sub {$Quit = 'SIGINT'};

# load config file
%Config = %{do(rfile('config/config.pl'))};

# initialize stuff
MCoreTools->open_log;
MConnection->listen_start;
MModules->load_modules;
MHelp->load_help;
MSocials->load;

MFreezer->initialize;
MObjectDB->initialize;
MIndex->initialize;

MBootstrap->startup_checks; # must be after DB and index init

### Main loop ############################################################################################

$Quit = undef;

MScheduler->run;

### Shutdown ###############################################################################################

END {
  # Cause of exit indicated by $Quit:
  #   false: crash
  #   'normal': admin shutdown command
  #   anything else: string describing reason

  if (!$Quit) {
    mudlog "Exiting due to crash.";
    MConnection->all->send("*** Sorry, but $Config{name} just crashed. ***");
    $? = 1;
  } elsif ($Quit eq 'normal') {
    mudlog "Exiting normally.";
    MConnection->all->send("*** $Config{name} is shutting down. ***");
    $? = 0;
  } elsif ($Quit eq 'restart') {
    mudlog "Exiting for restart.";
    MConnection->all->send("*** $Config{name} is restarting. ***");
    $? = 0;
  } else {
    mudlog "Exiting due to $Quit.";          
    MConnection->all->send("*** $Config{name} is shutting down. ***");
    $? = 1;    
  }
  mudlog "Closing listener...";
  MConnection->listen_stop;
  mudlog "Closing database...";
  MObjectDB->close;
  mudlog "Disconnecting players...";
  MConnection->all->disconnect('shutdown');
  mudlog "Exit cleanup complete.";
  if (!$Quit or $Quit eq 'restart') {
    if ($^O eq 'MacOS') {
      # I like Mac OS, but this is UGLY.
      MacPerl::DoAppleScript(do { $_ = <<'      EOSC'; s/THEPATH/"$0"/; $_ });
        ignoring application responses
          tell app "Finder" to open file THEPATH
        end ignoring
      EOSC
    } else {
      
      exec ('/usr/bin/perl', '-wT', rfile('engine/mpMUD.pl')) or die "Couldn't re-exec self: $!";
    }
  }
}
1;

__END__
