The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl 

use strict;
use CGI;
use Bio::Graphics::Browser2;
use Bio::Graphics::Browser2::Render::HTML;

umask 022;

my $fcgi    = Bio::Graphics::Browser2::Render->fcgi_request;
my $init;

if ($fcgi) {
    my $FCGI_DONE = 0;
    $SIG{USR1} = $SIG{PIPE} = $SIG{TERM} = sub {
	my $sig  = shift;
	my $time = localtime;
	print STDERR "[$time] [notice] GBrowse FastCGI process caught sig$sig. Exiting... (pid $$)\n";
	$FCGI_DONE = 1;
    };

    my %sys_env = %ENV;
    my $globals = Bio::Graphics::Browser2->open_globals;
    warn "[$$] FastCGI initializing and loading default data sources...\n";
    foreach ($globals->data_sources) {
	warn "[$$] Loading $_\n";
	my $source = $globals->create_data_source($_);
	$source->open_database();  # cache default database in memory
    }
    
    while (!$FCGI_DONE) {
	my $status = $fcgi->Accept;
	next unless $status >= 0;
        %ENV = (%sys_env, %ENV);
	CGI->initialize_globals();
	my $render = Bio::Graphics::Browser2::Render::HTML->new($globals);
	eval {
	    local $SIG{PIPE} = sub {die "pipe"};
	    $render->run();
	};
	warn $@ if $@;
	$render->destroy;
    }

    my $pgrp = getpgrp();
    kill TERM => -$pgrp;

} else {
    $SIG{TERM} = sub { warn "[$$] gbrowse going down..."; CORE::exit 0 };
    my $globals = Bio::Graphics::Browser2->open_globals;
    Bio::Graphics::Browser2::Render::HTML->new($globals)->run();
}

exit 0;