#/*
# *  Copyright 2007-2010 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 1912 2010-01-01 13:46:30Z hikarin $
#

package Img0ch::PSGI::BootStrap;

use strict;
use CGI::PSGI;
use File::Basename qw();
use Img0ch::PSGI::Request qw();

sub run {
    my ( $iClass, $iConfig, $env ) = @_;
    my ($file) = $env->{'REQUEST_URI'} =~ m{/([\w\-]+\.cgi)}xms;
    my $res = [];
    $env->{'PATH_INFO'} =~ s{\A/}{}xms;

    eval {
        my $app = Img0ch::Kernel->get_module_by_script($file);
        my $q   = CGI::PSGI->new($env);
        $app->new( Img0ch::Kernel->new($iConfig), $q )->run();
        my $headers = $q->param('img0ch.psgi.headers');
        my $body    = $q->param('img0ch.psgi.body');
        @$res = ( $q->psgi_header($headers), $body );
    };
    if ( my $errstr = $@ ) {
        $errstr = Img0ch::Kernel::escape_html_entities($errstr);
        $errstr =~ s/\n/<br>/gxms;
        $errstr =~ s/\s/&nbsp;/gxms;
        @$res = ( 500, [ 'Content-type' => 'text/html' ], [$errstr] );
    }
    $res;
}

1;
__END__
