our $booted = 1;

unlink 'booted';

open my $pidfile, '<', 'boot.pid';
my $pid = <$pidfile>;
close $pidfile;
chomp $pid;

if ( $pid ) {
    print STDERR "kill 'TERM' => $pid;";
    kill 'TERM' => $pid;
    select undef, undef, undef, 1;
    kill 'KILL' => $pid;
    print STDERR "kill 'TERM' => $pid;";

    unlink 'booted';
}

open $pidfile, '>', 'boot.pid';
print $pidfile $$;
close $pidfile;

*ORIG_STDERR = STDERR;
print STDERR 't.', "\n";

open *STDOUT, '>', '../boot.log';
open *STDERR, '>', '../boot-err.log';

$| = 1;

BEGIN { $ENV{DBI_PUREPERL}=1; *ORIG_STDERR = STDERR; }

$SIG{'INT'}  = 'IGNORE';
$SIG{'QUIT'} = 'IGNORE';
$SIG{'TERM'} = 'IGNORE';



my @files = qw{
./jeliza-auto-client.pl
./jeliza-auto-server.pl
./jeliza-batch.pl
./jeliza-cgi-engine.pl
./jeliza-cgi.fcgi
./jeliza-cgi.pl
./jeliza-cgi-simple.pl
./jeliza-console.pl
./jeliza-engine.pl
./jeliza-log.pl
./jeliza.pl
./jeliza-shell.pl
AI/SemanticEngine.pm
AI/SemanticNetwork.pm
AI/POS.pm
AI/FreeHAL/Module/Parser.pm
AI/FreeHAL/Module/Tagger.pm
AI/FreeHAL/Module/WebAccess.pm
AI/FreeHAL/Class.pm
AI/FreeHAL/Engine.pm
AI/FreeHAL/Config.pm
AI/Util.pm
AI/Selector.pm
./jeliza-service-tagger.pl
./perl.exe
./jeliza-proxy.pl
./jeliza-offer.pl
./File/Tee.pm
./lang_de/wsh/arts.wsh
./lang_de/wsh/first_names.wsh
./lang_de/wsh/names.wsh
./lang_de/wsh/no-names.wsh
./lang_de/word_types.memory
./lang_de/word_types.taggerinput
./DBI.pm
./DBI/PurePerl.pm
./DBD/SQLite.pm
./DBD/CSV.pm
SQL/Eval.pm
SQL/Dialects/ANSI.pm
SQL/Dialects/CSV.pm
SQL/Dialects/AnyData.pm
SQL/Parser.pm
SQL/GetInfo.pm
SQL/Functions.pm
SQL/Syntax.pod
SQL/Util.pm
SQL/ANSI.pm
SQL/Statement/GetInfo.pm
SQL/Statement/Functions.pm
SQL/Statement/Syntax.pod
SQL/Statement/Util.pm
SQL/Statement/RAM.pm
SQL/Statement/Structure.pod
SQL/Statement/Embed.pod
SQL/Statement.pm
SQL/RAM.pm
SQL/CSV.pm
SQL/Structure.pod
SQL/Embed.pod
SQL/AnyData.pm
Lingua/
Lingua/Identify.pm
Lingua/Stem
Lingua/Stem/De.pm
Lingua/Stem/Gl.pm
Lingua/Stem/Sv.pm
Lingua/Stem/Pt.pm
Lingua/Stem/AutoLoader.pm
Lingua/Stem/Da.pm
Lingua/Stem/En.pm
Lingua/Stem/No.pm
Lingua/Stem/EnBroken.pm
Lingua/EN
Lingua/EN/Tagger.pm
Lingua/EN/Tagger
Lingua/EN/Tagger/pos_tags.hash
Lingua/EN/Tagger/tags.yml
Lingua/EN/Tagger/pos_words.hash
Lingua/EN/Tagger/unknown.yml
Lingua/EN/Tagger/words.yml
Lingua/Identify
Lingua/Identify/AF.pm
Lingua/Identify/EU.pm
Lingua/Identify/MS.pm
Lingua/Identify/DE.pm
Lingua/Identify/PT.pm
Lingua/Identify/ES.pm
Lingua/Identify/RO.pm
Lingua/Identify/EO.pm
Lingua/Identify/FY.pm
Lingua/Identify/BG.pm
Lingua/Identify/HU.pm
Lingua/Identify/PL.pm
Lingua/Identify/FI.pm
Lingua/Identify/BS.pm
Lingua/Identify/HR.pm
Lingua/Identify/NL.pm
Lingua/Identify/SO.pm
Lingua/Identify/GA.pm
Lingua/Identify/NO.pm
Lingua/Identify/DA.pm
Lingua/Identify/LV.pm
Lingua/Identify/BR.pm
Lingua/Identify/IS.pm
Lingua/Identify/SQ.pm
Lingua/Identify/SW.pm
Lingua/Identify/CY.pm
Lingua/Identify/TR.pm
Lingua/Identify/SV.pm
Lingua/Identify/ET.pm
Lingua/Identify/SL.pm
Lingua/Identify/RU.pm
Lingua/Identify/ID.pm
Lingua/Identify/EN.pm
Lingua/Identify/FR.pm
Lingua/Identify/LA.pm
Lingua/Identify/IT.pm
Lingua/Identify/Nothing.pm
Lingua/DE
Lingua/DE/Wortschatz
Lingua/DE/Wortschatz/Result.pm
Lingua/DE/Tagger.pm
Lingua/DE/Wortschatz.pm
Lingua/DE/Tagger
Lingua/DE/Tagger/pos_tags.hash
Lingua/DE/Tagger/tags.yml
Lingua/DE/Tagger/pos_words.hash
Lingua/DE/Tagger/unknown.yml
Lingua/DE/Tagger/words.yml
Lingua/pm_to_blib
Lingua/Stem.pm
};

my @dirs = qw{
./AI
./AI/FreeHAL
./AI/FreeHAL/Module/
Lingua
Lingua/DE
Lingua/DE/Tagger
Lingua/EN
Lingua/EN/Tagger
Lingua/Identify
Lingua/Stem
./File
./lang_de
./lang_de/wsh
./DBD
./Net
./Digest
./MIME
./DBI
SQL/
SQL/Statement/
SQL/Dialects/
};

foreach my $n (0..10) {
    foreach my $dir (@dirs) {
        mkdir $dir;
    }
}

use LWP::Simple;

if ( 0 and -f 'do-batch' || $ARGV[0] =~/batch/i ) {
    # per chunk.
    sub callback {
       my ($data, $response, $protocol) = @_;
       $final_data .= $data;
       print ".";
    }

    my $content;
    my $file = "../freehal.tar.gz";
    print "downloading freehal.tar.gz\n";
    use LWP::UserAgent;
    my $ua = LWP::UserAgent->new(  );
    $ua->agent(
    "Mozilla/5.0 (X11; U; Linux i686; de; rv:1.8.1.10) Gecko/20071213 Firefox/2.0.0.1"
    );

    my $url1 = "http://jeliza.sourceforge.net/freehal.tar.gz";
    my $url2 = "http://resources.freehal.org/resources/download/freehal.tar.gz";

    foreach my $n (0..20) {
        my $response;
        eval {
            local $SIG{__DIE__} = 'IGNORE';
            local $SIG{ALRM} = sub { die @_ };
            
            alarm(60*10);
            
            $response = $ua->get($url1, ':content_cb' => \&callback, );
        };
        print $@ if $@;
        alarm(0);
        
        $content = $response->content || $response;
        if ( $content && length($content) > 100 ) {
            open my $file, '>', $file;
            print { $file } $content;
            close $file;
            last;
        }
        else {
            eval {
                local $SIG{__DIE__} = 'IGNORE';
                local $SIG{ALRM} = sub { die @_ };
                
                alarm(60*10);
                
                $response = $ua->get($url2, ':content_cb' => \&callback, );
            };
            print $@ if $@;
            alarm(0);
        
            $content = $response->content || $response;
        
        }
        if ( $content && length($content) > 100 ) {
            open my $file, '>', $file;
            print { $file } $content;
            close $file;
            last;
        }
    }

    if ( lc($^O) =~ /win/i ) {
        system("tar -xzf ..\\freehal.tar.gz");
    }
    else {
        system("tar -xzf ../freehal.tar.gz");
    }
}
else {
    foreach my $file (@files) {
        if ( ($file =~ /lang|SQL|Lingua/ || -f 'no-download') && -f $file ) {
            print "NOT downloading ", $file, "\n";
            next;
        }
        
        print "downloading ", $file, "\n";
        # $content = get("http://resources.freehal.org/resources/download/".$file.".txt");
        $content = get("http://jeliza.svn.sourceforge.net/svnroot/jeliza/bdata/".$file);
        if ( $content ) {
            # print $content;
            open my $file, '>', $file;
            print { $file } $content;
            close $file;
        }
    }
}


print "Download finished.\n";

my $lang = 'lang_de';
my $action = shift;
if ( length($action) == 2 ) {
    $lang = $action;
    $action = shift;
}
else {
    $lang = shift || $lang;
}

print "Actions?.\n";
if ( $action ) {
    opendir( my $dir, '.' );
    foreach my $file (readdir($dir)) {
        next if $file !~ /do[-]/;
        print "deleting ", $file, "\n";
        unlink $file;
    }
    my $file = 'do-'.$action;
    print "creating ", $file, "\n";
    open my $f, '>', $file;
    close $f;
}

print "Languages?.\n";
#select undef, undef, undef, 5;
opendir( my $dir, '.' );
foreach my $may_be_lang (readdir($dir)) {
    next if $may_be_lang !~ /lang_/;
    if (    -f $may_be_lang . '/default'
         || -f $may_be_lang . '/default.txt' ) {
        
        print "Language ", $may_be_lang, " is default.\n";
        $lang = $may_be_lang;
    }
    else {
        print "Language ", $may_be_lang, " is NOT default.\n";
    }
}

#select undef, undef, undef, 5;

$lang =~ s/lang_//igm;

print "So, the default is: $lang\n";

mkdir "temp";
open my $lang_file, ">", "temp/language.tmp";
print $lang_file $lang;
close $lang_file;


open my $file, '>', 'booted';
close $file;

$lang =~ s/lang_//igm;

unshift @ARGV, $lang;

if ( -f 'do-batch' ) {
    require("./jeliza-batch.pl");
}
elsif ( -f 'do-autoserver' ) {
    require("./jeliza-auto-server.pl");
}
elsif ( -f 'do-server' ) {
    require("./jeliza.pl");
}
elsif ( -f 'do-proxy' ) {
    require("./jeliza-proxy.pl");
}
elsif ( -f 'do-shell' ) {
    require("./jeliza-shell.pl");
}

1;