#!/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;

    warn "[$$] FastCGI initializing and loading default data sources...\n";
    my $globals = Bio::Graphics::Browser2->open_globals;
    if($globals->preload_datasources) {
      foreach ($globals->data_sources) {
        warn "[$$] Loading $_\n";
        my $source = $globals->create_data_source($_);
        $source->open_database();  # cache default database in memory
      }
    }
    else {
      warn "[$$] Preload disabled";
    }

    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;
