#!/usr/bin/perl

# First of all, let's load HELM configuration
use Env;
my $HELM_CONFIGURATION_PREFIX = $ENV{"HELM_CONFIGURATION_PREFIX"};
my $HELM_CONFIGURATION_PATH =
 $HELM_CONFIGURATION_PREFIX."/local/lib/helm/configuration.pl";
# next require defines: $helm_dir, $html_link, $dtd_dir, $uris_dbm
require $HELM_CONFIGURATION_PATH;



use HTTP::Daemon;
use HTTP::Status;
use HTTP::Request;
use LWP::UserAgent;
use DB_File;

#CSC: mancano i controlli sulle condizioni di errore di molte funzioni
#CSC: ==> non e' robusto
#CSC: altra roba da sistemare segnata con CSC

my $d = new HTTP::Daemon LocalPort => 8081;
tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
print "Please contact me at: <URL:", $d->url, ">\n";
print "helm_dir: $helm_dir\n";
print "dtd_dir: $dtd_dir\n";
print "urls_of_uris.db: $uris_dbm.db\n";
$SIG{CHLD} = "IGNORE"; # do not accumulate defunct processes
$SIG{USR1} = \&update; # sent by the child to make the parent update
while (my $c = $d->accept) {
 if (fork() == 0) {
    while (my $r = $c->get_request) {
        #CSC: mancano i controlli di sicurezza
        
        my $inputuri = $r->url; 
        $inputuri =~ s/^[^?]*\?uri=(.*)/$1/;
        print "\nRequest: ".$r->url."\n\n";
        my $http_method = $r->method;
        my $http_path = $r->url->path;

        if ($http_method eq 'GET' and $http_path eq "/getciconly") {
            # finds the uri, url and filename
            my $cicuri = $inputuri;

            my $cicfilename = $cicuri;
            $cicfilename =~ s/cic:(.*)/$1/;
            $cicfilename =~ s/theory:(.*)/$1/;
            $cicfilename = $helm_dir.$cicfilename.".xml";

            my $cicurl   = $map{$cicuri};
            if (!defined($cicurl)) {
             print "\nNOT FOUND!!!!!\n";
             $c->send_error(RC_NOT_FOUND)
            } else {
               print_request("cic",$cicuri,$cicurl,$cicfilename);

               # Retrieves the file
               my $ciccontent = download(0,"cic",$cicurl,$cicfilename);

               # Answering the client
               answer($c,$ciccontent);
            }
        } elsif ($http_method eq 'GET' and $http_path eq "/get") {
            # finds the uris, urls and filenames
            my $cicuri = $inputuri,
               $typesuri = $inputuri,
               $annuri = $inputuri;
            my $annsuffix;
            if ($inputuri =~ /\.types$/) {
               $cicuri    =~ s/(.*)\.types$/$1/;
               undef($annuri);
            } elsif ($inputuri =~ /\.types\.ann$/) {
               $cicuri    =~ s/(.*)\.types\.ann$/$1/;
               $typesuri  =~ s/(.*)\.ann$/$1/;
               $annsuffix = ".types.ann";
            } elsif ($inputuri =~ /\.ann$/) {
               $cicuri  =~ s/(.*)\.ann$/$1/;
               undef($typesuri);
               $annsuffix = ".ann";
            } else {
               undef($typesuri);
               undef($annuri);
            }

            my $cicfilename = $cicuri;
            $cicfilename =~ s/cic:(.*)/$1/;
            $cicfilename =~ s/theory:(.*)/$1/;
            $cicfilename = $helm_dir.$cicfilename;

            my $typesfilename = $cicfilename.".types.xml"     if $typesuri;
            my $annfilename  = $cicfilename.$annsuffix.".xml" if $annuri;
            $cicfilename .= ".xml";

            my $cicurl   = $map{$cicuri};
            my $typesurl = $map{$typesuri} if $typesuri;
            my $annurl   = $map{$annuri}  if $annuri;

            if (!defined($cicurl) ||
               (!defined($typesurl) && $typesuri) ||
               (!defined($annuri) && $annuri))
            {
             print "\nNOT FOUND!!!!!\n";
             $c->send_error(RC_NOT_FOUND)
            } else {
               print_request("cic",$cicuri,$cicurl,$cicfilename);
               print_request("types",$typesuri,$typesurl,$typesfilename)
                if ($typesuri);
               print_request("ann",$annuri,$annurl,$annfilename)
                if ($annuri);
 
               # Retrieves the files

               my $ciccontent = download(1,"cic",$cicurl,$cicfilename);
               my $typescontent =
                download(1,"types",$typesurl,$typesfilename) if ($typesuri);
               my $anncontent =
                download(1,"ann",$annurl,$annfilename) if ($annuri);
 
               # Merging the files together
 
               my $merged = <<EOT;
<?xml version="1.0" encoding="UTF-8"?>
<cicxml uri="$cicuri">
$ciccontent
$typescontent
$anncontent
</cicxml>
EOT

               # Answering the client
               answer($c,$merged);
            }
         } elsif ($http_method eq 'GET' and $http_path eq "/getdtd") {
            my $filename = $inputuri;
            $filename = $dtd_dir."/".$filename;
            print "DTD: $inputuri ==> ($filename)\n";
            if (stat($filename)) {
               print "Using local copy\n";
               open(FD, $filename);
               $cont = "";
               while(<FD>) { $cont .= $_; }
               close(FD);
               answer($c,$cont);
            } else {
               die "Could not find DTD!";
            }
        } elsif ($http_method eq 'GET' and $http_path eq "/conf") {
            my $quoted_html_link = $html_link;
            $quoted_html_link =~ s/&/&amp;/g;
            $quoted_html_link =~ s/</&lt;/g;
            $quoted_html_link =~ s/>/&gt;/g;
            $quoted_html_link =~ s/'/&apos;/g;
            $quoted_html_link =~ s/"/&quot;/g;
            print "\nConfiguration requested, returned #$quoted_html_link#\n";
	    $cont = "<?xml version=\"1.0\"?><html_link>$quoted_html_link</html_link>";
            answer($c,$cont);
        } elsif ($http_method eq 'GET' and $http_path eq "/update") {
           print "Update requested...";
           update();
           kill(USR1,getppid());
           print " done\n";
           answer($c,"<html><body><h1>Update done</h1></body></html>");
        } else {
            print "\nINVALID REQUEST!!!!!\n";
            $c->send_error(RC_FORBIDDEN)
        }
        print "\nRequest solved: ".$r->url."\n\n";
    }
    $c->close;
    undef($c);
    print "\nCONNECTION CLOSED\n\n";
    exit;
  } # fork
}

#================================


#CSC: Too much powerful: creates even /home, /home/users/, ...
#CSC: Does not raise errors if could not create dirs/files
sub mkdirs
{
 my ($pathname) = @_;
 my @dirs = split /\//,$pathname;
 my $tmp;
 foreach $dir (@dirs) {
  $tmp = ((defined($tmp)) ?  $tmp."\/".$dir : "");
  mkdir($tmp,0777);
 }
 rmdir($tmp);
}

sub print_request
{
 my ($str,$uri,$url,$filename) = @_;
 print $str."uri: $uri\n";
 print $str."url: $url\n";
 print $str."filename: $filename\n\n";
}

sub callback
{
 my ($data) = @_;
 $cont .= $data;
}

sub download
{
 my ($remove_headers,$str,$url,$filename) = @_;
 $cont = ""; # modified by side-effect by the callback function
 if (stat($filename)) {
    print "Using local copy for the $str file\n";
    open(FD, $filename);
    while(<FD>) { $cont .= $_; }
    close(FD);
 } else {
    print "Downloading the $str file\n";
    $ua = LWP::UserAgent->new;
    $request = HTTP::Request->new(GET => "$url");
    $response = $ua->request($request, \&callback);
               
    print "Storing the $str file\n";
    mkdirs($filename);
    open(FD, ">".$filename);
    print FD $cont;
    close(FD);
 }
 if ($remove_headers) {
    $cont =~ s/<\?xml [^?]*\?>//sg;
    $cont =~ s/<!DOCTYPE [^>]*>//sg;
 }
 return $cont;
}

sub answer
{
 my ($c,$cont) = @_;
 my $res = new HTTP::Response;
 $res->content($cont);
 $c->send_response($res);
}

sub update {
 untie %map;
 tie(%map, 'DB_File', $uris_dbm.".db", O_RDONLY, 0664);
}
