#/*
# *  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 802 2007-06-10 12:47:54Z hikarin $
#

package Img0ch::FCGI::BootStrap;

use strict;
use File::Basename qw();
use FCGI::ProcManager qw();
use Img0ch::Config qw();
use Img0ch::FCGI::Request qw();
use Img0ch::Maple qw();

my $img0ch_config_modified = 0;

sub import {
    my ( $iBootstrap, $app ) = @_;
    my $iConfig = Img0ch::Config->new();
    eval "use ${app} qw(); 1" or die $@, "\n";

    my $processes = $ENV{PM_N_PROCESSES} || 5;
    my $FCGIPM = FCGI::ProcManager->new( { n_processes => $processes } );
    $FCGIPM->pm_manage();

    require CGI::Fast;
SERVER:
    while ( my $q = CGI::Fast->new() ) {
        $FCGIPM->pm_pre_dispatch();
        my $base     = $ENV{SCRIPT_FILENAME} || $0;
        my $path     = File::Basename::dirname($base) . '/img0ch-config.cgi';
        my $modified = ( stat($path) )[9];
        if ( ( $img0ch_config_modified ||= $modified ) < $modified ) {
            my $message = join '', '[', scalar( localtime( time() ) ),
                '] restarted FastCGI application: ', $app, "\n";
            $FCGIPM->pm_die($message);
        }
        eval {
            $iConfig->load($path);
            $app->new( Img0ch::Maple->new($iConfig), $q )->run();
        };
        if ( my $errstr = $@ ) {
            $errstr = Img0ch::Maple::escape_html_entities($errstr);
            $errstr =~ s/\n/<br>/gxms;
            $errstr =~ s/\s/&nbsp;/gxms;
            print 'Content-type: text/html', "\n\n", $errstr, "\n";
        }
        $FCGIPM->pm_post_dispatch();
    }
}

1;
__END__
