#/*
# *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: BootStrap.pm 432 2007-03-27 13:51:06Z hikarin $
#

package Img0ch::FCGIA::BootStrap;

use strict;
use CGI::Minimal qw(:preload);
use FCGI::Async qw();
use File::Basename qw();
use File::Temp qw();
use IO::Async::Set::IO_Poll qw();
use Img0ch::Config qw();
use Img0ch::FCGIA::Request qw();
use Img0ch::Maple qw();

sub import {
    my ( $iBootstrap, $app ) = @_;
    my $iConfig = Img0ch::Config->new();
    my $io = IO::Async::Set::IO_Poll->new();

    $io->add(FCGI::Async->new(on_request => sub {
        my ( $fcgi, $r ) = @_;
        my $base = $r->param('SCRIPT_FILENAME') || $0;
        my $path = File::Basename::dirname($base);
        eval {
            $iConfig->load("${path}/img0ch-config.cgi");
            my $iKernel = Img0ch::Maple->new($iConfig);
            my $file = $app;
            $file =~ s{::}{/}gxms;
            $file .= '.pm';
            $app->new( $iKernel, $r )->run();
        };
        if ( my $errstr = $@ ) {
            $errstr = Img0ch::Maple::escape_html_entities($errstr);
            $errstr =~ s/\n/<br>/gxms;
            $errstr =~ s/\s/&nbsp;/gxms;
            $r->print_stdout('Content-type: text/html');
            $r->print_stdout("\n\n${errstr}\n");
        }
        $r->finish();
    }));
    $io->loop_forever();
}

1;
__END__
