#!/usr/bin/perl
use FCGI;
use CGI;
use mapscript;
use IO::Handle;

sub timestamp {
  my ($d,$t);
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

        $year += 1900;
        $mon++;
        $d = sprintf("%4d-%2.2d-%2.2d",$year,$mon,$mday);
        $t = sprintf("%2.2d:%2.2d:%2.2d",$hour,$min,$sec);
        return($d,$t);
}

sub ImageRenderer {
  local ($map_file,$map,$img,$layer);
  
  open(MYOUTFILE, ">/tmp/logfile-$$.log");
  MYOUTFILE->autoflush(1);
print( "Content-Type: text/plain", "\n\n" );
print MYOUTFILE "PID:$$\nStart:";
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 

print MYOUTFILE "Creazione mappa:";
  $map_file='/home/mapserver/etc/mapserver/mapfile/RegionePiemonte.map';
  die mapscript::ms_error->{message} unless my $map = new mapscript::mapObj( $map_file );
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 

print MYOUTFILE "Reperimento layer:";  
  die mapscript::ms_error->{message} unless my $layer = $map->getLayerByName($_[0]);
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 
print MYOUTFILE "Preparazione Immagine:";
  $map->setImageType('GD/PNG');
  $img = $map->prepareImage();
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 
print MYOUTFILE "Disegno:";
  $layer->draw($map, $img); # draw basemap
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 
print MYOUTFILE "Salvo:";
  $img->save('/dev/null');
print MYOUTFILE &timestamp(); 
print MYOUTFILE "\n"; 
print MYOUTFILE "Fine\n";
  close(MYOUTFILE);
  unlink("/tmp/logfile-$$.log");
  
}

my $query = new CGI;
# my $FCGIquery =  FCGI::Request();

# if ($FCGIquery->IsFastCGI()) { #FastCGI
#   while( FCGI::accept() >= 0 )
#   {
# #    ImageRenderer($query->param('LAYER'));
#    print( "Content-Type: text/plain", "\n\n" );
#    print( "FastCGI is there!", "\n" );
#   }
# } else { #CGI
my $layer;

if ($query->param('LAYER')) {$layer=$query->param('LAYER');}
else {$layer="CTR-SDE"}

  ImageRenderer($layer);
  exit(0);
#   
# } #end CGI part







