#/*
# *  Copyright 2007-2009 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 1826 2009-04-08 15:23:25Z hikarin $
#

package Img0ch::FCGI::Async::BootStrap;

use strict;
use FCGI::Async 0.11 qw();
use File::Basename qw();
use IO::Async::Set::IO_Poll qw();
use Img0ch::Config qw();
use Img0ch::FCGI::Async::Request qw();
use Img0ch::Maple qw();

my $img0ch_config_modified = 0;

sub import {
    my ( $iBootstrap, $app ) = @_;
    my $iConfig = Img0ch::Config->new();
    Img0ch::Maple->load_module($app);

    my $class = 'IO::Async::Set::'
        . ( $iConfig->get('fcgi.async_set_module') || 'IO_Poll' );
    Img0ch::Maple->load_module($class);
    my $io = $class->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) . '/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";
                    $r->print_stderr($message);
                    $r->finish(1);
                }
                eval {
                    $iConfig->load($path);
                    $app->new( Img0ch::Maple->new($iConfig), $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\n\n$errstr\n");
                }
                $r->finish(0);
            }
        )
    );
    $io->loop_forever();

    return 0;
}

1;
__END__
