package bscgi;

my $fcgi = 0;
my $deftimeout = 120;
my %skinc;

eval {
    require FCGI;
    $fcgi = 1;
};

use bbdisp;

sub init {
    unless( $BigSister::common::display ) {
	$BigSister::common::display = new bbdisp( );
    }
}


sub mainloop {
    my( $func, $skinset, $timeout ) = @_;
    my $go_on = 1;

    init();
    ($timeout = $deftimeout) unless( $timeout );
    $SIG{"ALRM"} = sub { exit(0); };

    while( $go_on ) {
	$go_on = $fcgi;
	if( $fcgi ) {
	    alarm($timeout);
	    last unless( FCGI::accept() >= 0 );
	    my $len = $ENV{"CONTENT_LENGTH"};
	    alarm(0);
	}
	my $query;
	my $data="";
	my $len = 0 + $ENV{'CONTENT_LENGTH'};
	if($len > 0) {
	    my $i;
	    for($i = 0; $i < $len; $i++) {
		my $ch;
		$ch = getc(STDIN);
		last unless( $ch );
		$data .= $ch;
	    }
	}       
	if( $data ) {
	    $query = $data;
	}
	else {
	    $query = $ENV{"QUERY_STRING"};
	}
	my %cgivars;
	my $i;

	if( $ARGV[0] eq "-d" ) {
		foreach my $arg (@ARGV) {
			if( $arg =~ /^([a-z]+)=(.*)/i ) {
			$cgivars{$1} = $2;
			$cgivars{"\@$1"} = [$2];
			}
		}
	}

	for (split( "&", $query )) {
	    if( /^([A-Z]+)=(.*)/i ) {
		my( $var, $val ) = ($1,$2);
		$val =~ s/\+/ /g;
		while( $val =~ /\%([0-9a-f]{2})/i ) {
		    $val = $`.sprintf("%c",hex($1)).$';
		}
		$val =~ s/\"/\'/g;
		if( defined $cgivars{$var} ) {
		    push( @{$cgivars{"\@$var"}}, $val );
		}
		else { 
		    $cgivars{$var} = $val;
		    $cgivars{"\@$var"} = [$val];
		}
	    }
	}
	$cgivars{"EXPIRES"} = Platform::strftime("%a, %d %h %Y %T GMT", time + 60);
	my $skins = $skinset;
	BigSister::common::load_resources();
	if( $BigSister::common::resources{"skin"} ) {
	    $skins = $BigSister::common::resources{"skin"};
	}
	if( $cgivars{"SKIN"} ) {
	    $skins = $cgivars{"SKIN"};
	}
	if( defined $skinc{$skins} ) {
	    $skins = $skinc{$skins};
	}
	else {
	    my $l;
	    my $skin;
	    foreach $l ( "default", split( ",", $skinset ), split(",",$skins) ) {
		$skin = $BigSister::common::display->read_skin( $l, $skin );
	    };
	    $skinc{$skins} = $skin;
	    $skins = $skin;
	    $skins->{"_BASE"} = $BigSister::common::display->get_skin( $skin, "WEBROOT.inc" );
	}
	&$func( $skins, %cgivars );
    };
}


sub myurl {
    my( $path ) = @_;
    my $port = $ENV{"SERVER_PORT"};
    my $proto = ($port == 443)?"https":"http";
    my $server_name = $ENV{"SERVER_NAME"};
    ($path = $ENV{"SCRIPT_NAME"}) unless( $path );
    return( "$proto://$server_name".((($port == 80) || ($port == 443))?"":":$port")."$script_name" );
}

1;
