#!/usr/bin/perl -w

# start from command-line as user = <apache web-user>

use strict;

BEGIN { 
    use FindBin qw($Bin); # warn 'BIN:'.$Bin;
    # set lib paths for app:
    use lib (
        '/home/raj/perl5/lib/perl5',
        "$Bin/../lib",
        "$Bin/..",
    );
}

use FCGI; 
use CGI::Fast();
use LIMS::Dispatch;
use FCGI::ProcManager;
# use Data::Dumper; $Data::Dumper::Useperl = 1; # prevent XS Dumper - maybe bug in 5.8.8

my $socket  = FCGI::OpenSocket( '/tmp/hilis4.socket', 2 ); # path, backlog
my $request = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%ENV, $socket );

my $proc_manager = FCGI::ProcManager->new({ n_processes => 3 });

$proc_manager->pm_manage();

$CGI::Fast::Ext_Request = $request;

while ( my $query = CGI::Fast->new() ) {
	# set active db to production - default is `test`:
    $ENV{ROSEDB_DEVINIT} = "$Bin/../config/rosedb_devinit_prod.pl";
    # set flag for LIMS::_set_cgisession_options & QueryLog:
    $ENV{FAST_CGI} = 1;
	# set DBI trace:
	# $ENV{DBI_TRACE} = "1=$Bin/../logs/trace.log";
	
	$ENV{RDBO_DEBUG} = 1; # switch LIMS::RDBO $Rose::DB::Object::Debug on
	
    $proc_manager->pm_pre_dispatch();
    
    eval {
        LIMS::Dispatch->dispatch(
            args_to_new => { QUERY => $query },
            default => '',
            debug => 0,
        );
    };
	my $err = $@;
	if ($err) {
		warn "$0 error: $err";
		exit 0; # to free $dbh from stuck transaction and restart process(es)
	}
	
	$proc_manager->pm_post_dispatch();
}

FCGI::CloseSocket( $socket );

=begin # only increments count every n_processes => $n browser refreshes

my $cgi;
my $count = 0;
while ( $request->Accept() >= 0 ) {
	$proc_manager->pm_pre_dispatch();

	print header(); 
	print start_html();
	print img({-src => '/static/images/logo.jpeg'});
	print p( ++$count );
	print end_html();
}
=cut
