package Mud::Boot;
use strict;
use 5.004;

use Mud::FS;

=head1 Description

Mud::Boot provides the main initialization routine for mpMUD.

It also creates a default world if none is found.

=head1 Methods

=over 4

=cut

##############################################################################

=item CM boot(DIR)

Boots the mud, using DIR as the root for loading configuration files and world
data. This method will not return until the mud shuts down.

=cut

sub boot {
  my ($self, $dir) = @_;
  
  ###
  
  foreach (keys %ENV) {delete $ENV{$_}} # for security
  
  #####################################
  # Private initialization
  
  require Mud::CoreTools;
  Mud::CoreTools->initialize(root => $dir);

  #####################################
  # Prepare file system
  
  require Mud::FS;
  Mud::FS->mkpath('');
  
  #####################################
  # Load configuration
  
  my %config;
  if (Mud::FS->exists('config.pl')) {
    local $/;
    my $cfh = Mud::FS->open('config.pl', '<') or die $!;
    <$cfh> =~ /^(.*)$/s;
    eval $1; die $@ if $@;
  } else {
    %config = (
      bootstrap_storage => 'Mud::Storage::NamedFiles',
      bootstrap_key => 'boot',
      preferred_storage => 'Mud::Storage::NamedFiles', # FIXME
    );
    
    #my $cfh = Mud::FS->open('config.pl', '>') or die $!;
    #require Data::Dumper;
    #$cfh->print(Data::Dumper->Dump([\%config], ['*config']));
  }
  
  #####################################
  # Load modules just so we don't have to do it later
  
  require Mud::Scheduler;
  
  require Mud::Storage;
  require Mud::Storage::Ephemeral;
  require Mud::Storage::NamedFiles;

  require Mud::Obj;
  require Mud::Obj::Attributed;
  require Mud::Obj::Event;
  
  require Mud::Connection;
  require Mud::Connection::Handle;

  #####################################
  # Establish preferred storage status
  
  $config{preferred_storage}->register_storage('');

  #####################################
  # Bootstrap the world

  my $bobj = $config{bootstrap_storage}->obj($config{bootstrap_key})
    or print "dying\n", die "Bootstrap object #$config{bootstrap_key} not found!";
  Mud::Scheduler->add($bobj);
  Mud::Scheduler->run;
}

##############################################################################

=back

=cut

1;
__END__
