#!/usr/bin/perl 

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

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

umask 022;

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

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;
    while (!$FCGI_DONE) {
	my $status = $fcgi->Accept;
	next unless $status >= 0;
        %ENV = (%sys_env, %ENV);
	my $globals = Bio::Graphics::Browser2->open_globals;
	CGI->initialize_globals();
	my $render =Bio::Graphics::Browser2::Render::HTML->new($globals);
	$render->run();
	$render->destroy;
    }
} 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;
