#! /usr/bin/perl

use strict;

# Add here the pages of the documentation generated by a @page doxygen macro
my @extra_files = qw(html/faq.html html/history.html html/contrib.html html/people.html
                     html/publis.html html/publis_core.html html/publis_extern.html html/publis_intra.html);


my %debug;
$debug{'parse'} = 0; # show how we parse the module tree
$debug{'input'} = 0; # display the resulting tree
$debug{'handle'}= 0; # Be verbose on the post-processing
$debug{'rename'}= 0; # do not overwrite the files (allows several debuging runs without rerunning doxygen)

my @allfiles;
###
### Get the module definitions
###

open IN, "html/modules.html" || die "Cannot parse html/modules.html. Did you really run doxygen?\n";

# pass headers
while (<IN>) {
  last if /group__SimGrid__API.html/;
}

# Parse the tree
my $top;
my $current;
my $entry;

# $current->{'label'}="ROOT";
# push @{$top->{'down'}},$current;
# print "Push $current '".($current->{'label'})."' as child of $top '".($top->{'label'})."'\n" if $debug{'parse'};
# $current=$top;
$top->{'label'}="ROOT";
print "Create ROOT $top\n" if $debug{'parse'};
$current=$top;


# Read the whole data to postprocess it a bit
my $in;
while (<IN>) {
    $in .= $_;
}
$in =~ s/<ul>/\n<ul>\n/sg;
foreach $_ (split(/\n/,$in)) {
    next unless length($_);
    next if ($_ =~ m|^</li>$|);
    print "  Seen '$_'\n" if $debug{'parse'};
  if (/<ul>/) {
    print "DOWN: $current '$current->{'label'}' -> " if $debug{'parse'};
    $current = $current->{'down'}[scalar @{$current->{'down'}} - 1];
    print "$current '$current->{'label'}'\n" if $debug{'parse'};
    next;
  }
  if (/<\/ul>/) {
    $current = $current->{'up'};
    print "UP to $current '$current->{'label'}'\n" if $debug{'parse'};
    next;
  }
  if (/<p>/) {
    last;
  }
  
  m|href="([^"]*)">([^<]*)</a>|; #"
  
  $entry = {};
  $entry->{'file'} = $1;  
  $entry->{'label'} = $2;
  $entry->{'up'} = $current;
  push @{$current->{'down'}},$entry;
  print "Push file:$1 label:'$2' as child of $current '$current->{'label'}'\n" if $debug{'parse'};
  push @allfiles,"html/$1";
}
close IN;

# Check each file for extra information (short name, extra childs)
sub extra_info {
  my $current=shift;

  if (defined($current->{'file'})) {
    open IN, "html/$current->{'file'}";
    while (<IN>) {
      if (/DOXYGEN_NAVBAR_LABEL/) {
        if (/DOXYGEN_NAVBAR_LABEL="([^"]*)"/) {#"
          print "Extra info from $current->{'file'}: label=$1, not $current->{'label'}\n" if $debug{'parse'};
          $current->{'label'}=$1;
        } else {
          die "Malformated DOXYGEN_NAVBAR_LABEL line in $current->{'file'}";
        }
      }
      if (/DOXYGEN_NAVBAR_CHILD/) {
        if (/DOXYGEN_NAVBAR_CHILD *"([^"]*)"=([^ ]*)/) {#"
          $entry = {};
          $entry->{'label'} = $1;
          $entry->{'file'} = $2;
          chomp($entry->{'file'});
          $entry->{'up'} = $current;
          push @{$current->{'down'}},$entry;
          print "Extra info from $current->{'file'}: New child $entry->{'label'}=$entry->{'file'}\n"  if $debug{'parse'};
        } else {
          die "Malformated DOXYGEN_NAVBAR_CHILD line in $current->{'file'}";
        }
      }
    }
  }
  
  foreach my $entry (@{$current->{'down'}}) {
    extra_info($entry);
  }  
}
extra_info($top);

## debug function
sub display {
  my $current=shift;
  my $level=shift;
  print "  " x $level;
  print "$current: ".$current->{'label'}." ($current->{'file'})\n";
  foreach my $entry (@{$current->{'down'}}) {
    display($entry,$level+1);
  }
}

display($top,0) if $debug{'input'};

###
### Generate the navbar
###

# the root deserves some special handling
open IN,"html/modules.html" || die;
open OUT,">html/modules.new.html" || die;
my $line;
while ($line = <IN>) {
  last if $line =~ /<h1>SimGrid Modules</;
  print OUT $line;
}

print OUT "<div class=\"tabs\">\n  <ul class=\"tablist\">\n";
foreach $current (@{ ${$top->{'down'}}[0]->{'down'} }) {
  print OUT "   <li><a href=\"$current->{'file'}\"><span>$current->{'label'}</span></a></li>\n";
}
print OUT "  </ul></div>\n";
print OUT $line;
while (<IN>) {
  print OUT $_;
}

close OUT;
close IN;
rename("html/modules.new.html","html/modules.html") unless $debug{'rename'};

# the publication pages deserves some special handling too
my %pub_tabs = ("publis.html"       =>"Reference publications",
                "publis_core.html"  =>"Other publication about SimGrid",
                "publis_extern.html"=>"External papers using SimGrid",
                "publis_intra.html"=>"Internal papers using SimGrid");
# force ordering
my @pub_titles = ("publis.html", "publis_core.html", "publis_extern.html", "publis_intra.html");
sub handle_pub{
    my $oldname = shift;
    my $newname = $oldname;
    $newname =~ s/\.html$/.new.html/;
 
#    print "Handle_pub($oldname -> $newname)\n";
    
    open IN,"html/$oldname" || die "Cannot open $oldname";
    open OUT,">html/$newname" || die "Cannot open $newname";
    my $line;
# BIG FAT WARNING : THIS HACK IS DEPENDANT OF THE DOXYGEN VERSION AND OUR TEXT (because of the string we are looking for, that is changing with doxygen version, either h1 or div class="title" ... So we're forced to use titles defined in doc files...
    while ($line = <IN>) {
	$line =~ s/<h1>/<h1 align="center">/g;
	last if (($line =~ /Reference publications about SimGrid/) 
		or ($line =~  /Publications about the SimGrid framework/) 
		or ($line =~  /Papers that use SimGrid-generated results/) 
		or ($line =~  /Our own papers that use SimGrid-generated results/));
	print OUT $line;
    }

    print OUT "<div class=\"tabs\" align=\"center\">\n<ul class=\"tablist\">\n";
    foreach my $page (@pub_titles) {
	print OUT "         <li".($page eq $oldname? " class=\"current\"":"" )."> <a href=\"$page\"><span>".($pub_tabs{$page})."</span></a></li>\n";
    }

    print OUT "  </ul></div>\n";
    print OUT $line;
    while ($line = <IN>) {
	print OUT $line;
    }
    close OUT;
    close IN;
    rename("html/$newname","html/$oldname") unless $debug{'rename'};
}
map {handle_pub($_)} @pub_titles;


# Operate the recursion
sub handle_page {
  my $current=shift;
  my $level=shift;

  print "Handle $current->{'file'} at level $level\n" if $debug{'handle'};
    
  # we generate the tabs bottom up begining from where we are in the tree
  # and display them top down, as it should in a file
  my @tabs = ();
  my $found_div_tabs=0;
  
  if (defined ($current->{'label'}) and $current->{'label'} ne 'ROOT') {
#    print "handle $current->{'file'}, at level $level\n";
    # generate the tabs
    my $iterator = $current;
    my $lvl_it=$level;
    while ($lvl_it >= 0) {
      my $father = $iterator->{'up'};
      $tabs[$lvl_it] = "<div class=\"tabs2\">\n<ul class=\"tablist\">\n";
      foreach my $bro (@{$father->{'down'}}) {
        $tabs[$lvl_it] .= "  <li".($bro==$iterator?" class=\"current\"":"")."> <a href=\"$bro->{'file'}\"><span>$bro->{'label'}</span></a></li>\n";      
      }
      $tabs[$lvl_it] .= "  </ul></div>\n";
      $iterator = $father;
      $lvl_it--;
    }
    if (defined $current->{'down'}) { # there's some kid. Display them too
      $tabs[$level+1] = "<div class=\"tabs2\">\n  <ul class=\"tablist\">\n";
      foreach my $kid (@{$current->{'down'}}) {
        $tabs[$level+1] .= "  <li> <a href=\"$kid->{'file'}\"><span>$kid->{'label'}</span></a></li>\n";      
      }
      $tabs[$level+1] .= "  </ul></div>\n";      
    }
    
    # put them in place
    open FROM,"html/$current->{'file'}" || die;
    my $newname="html/$current->{'file'}";
    $newname =~ s/.html/.handlepage.html/;
    open TO,">$newname" || die;
#    print "XXX Deal with html/$current->{'file'}  ->  $newname\n";
    while (<FROM>) {
#      print "--Read  $_";
      # add "current" to the module API granfather page
      s|<li><a href="modules.html"><span>[^<]*</span></a></li>|<li class="current"><a href="modules.html"><span>Modules&nbsp;API</span></a></li>|;
#      print "++Write $_";
	  $found_div_tabs=1 if m/div.*class="tabs"/;	
      print TO "$_";
      last if ((m|</div>|)&&($found_div_tabs));
    }
      
    print TO "\n<!-- POST-PROCESSED TABS -->\n";
    foreach (@tabs) {
#      print "TAB: $_";
      print TO "$_";
    }
    print TO "\n<!-- END OF POST-PROCESSED TABS -->\n";
      
    if ($current->{'file'} =~ m/^class/) {
	  while (<FROM>) {
	 	last if (m|</div>|);
	  }
      print TO "$_";	
    }
    while (<FROM>) {
      if (m/POST-PROCESSED TABS/) {
	    while (<FROM>) {
	      last if (m/END OF POST-PROCESSED TABS/);
	    }
	    next;
      }

      if (m/The documentation for/) {
	    while (<FROM>) {
	      last if (m/<p>/);
	    }
      }
      print TO "$_";
    }
    close FROM;
    close TO;
    rename("$newname","html/$current->{'file'}") unless $debug{'rename'};
  } 
  
  # recurse on childs
  foreach my $entry (@{$current->{'down'}}) {
    handle_page($entry,$level+1);
  }
}

###
### Launch the modules navbar reworking
###
handle_page($top,-1);# skip roots (we have 2 roots) in level counting

###
### Add the modules navbar reworking to the modules.html file
###
sub add_tabs_to_module_html {
  my $found_div_tabs=0;
  my $module_tabs = "<div class=\"tabs2\">\n<ul class=\"tablist\">\n";
  foreach my $entry (@{$top->{'down'}}) {
      $module_tabs .= "  <li> <a href=\"$entry->{'file'}\"><span>$entry->{'label'}</span></a></li>\n";
  }
  $module_tabs .= "  </ul></div>\n";      
  
  my $oldname = "html/modules.html";
  open FROM,$oldname || die;
  my $newname=$oldname;
  $newname =~ s/.html/.handlepage.html/;
  open TO,">$newname" || die;
  while (<FROM>) {
    $found_div_tabs=1 if m/div.*class="tabs"/;	
	print TO "$_";
	last if ((m|</div>|)&&($found_div_tabs));
  }
  
  print TO "\n<!-- POST-PROCESSED TABS -->\n";
  print TO $module_tabs;
  print TO "\n<!-- END OF POST-PROCESSED TABS -->\n";

  while (<FROM>) {
	print TO "$_";
  }  
  close FROM;
  close TO;
  rename($newname, $oldname) unless $debug{'rename'};
  
  # die;
}   

add_tabs_to_module_html;

###
### Post-processsing common to all pages
###
map {push @allfiles,$_} @extra_files;
print "All files: ".(join(", ",@allfiles))."\n" if $debug{'parse'};

my $tabs;

foreach my $file (@allfiles) {
    $file =~ s/.html/.handlepage.html/ if $debug{'rename'}; # Take right name if debugging
	
    open FROM,"$file" || die;
    my $outfile = "$file";
    $outfile =~ s/.(html|php)$/.new.$1/;
    open TO,">$outfile" || die;
#    print "POSTPROCESSING $file (tmp=$outfile)\n";
    while (<FROM>) {
	


	  if($tabs){
		  if($file =~ /^html\/index\..*/){
		  	$_ =~ s/<li class="current">/<li>/g;
		  	$_ =~ s/<li><a href="index.html">/<li class="current"><a href="index.html">/g;
		  }		  
		  $_ =~ s/<li class="current"><a href="pages.html">/<li><a href="pages.html">/g;
		  
		  if($file =~ /^html\/pages\..*/){
		  	$_ =~ s/<li><a href="pages.html">/<li class="current"><a href="pages.html">/g;
		  }
	  }
	  
	  if($file =~ /^html\/publis.*/){
		  	$_ =~ s/<div class="header">/<div>/g;
		  	$_ =~ s/<div class="headertitle">/<div>/g;
	 }
	
	  # Add the FAQ PUBLIS PEOPLE HISTORY and CONTRIB to the top navbar.
      if( $_ =~ /<div.*class="tabs">/){
      	$tabs = 1;
      }
      if( $_ =~ /<\/div>/){
      	$tabs = 0;
      }
      if( $_ =~ /<\/ul>/ && $tabs){
      		my $tmp_buff="";
		
			# LBO : ugly way to separate doc in 2 separate stuff ...
			$tmp_buff .= '      <li><a href="https://gforge.inria.fr/frs/?group_id=12"><span>Download</span></a></li>'."\n";
	      		$tmp_buff .= '      <li><a href="documentation.html"><span>Online documentation</span></a></li>'."\n";
	      		$tmp_buff .= '      <li><a href="publis.html"><span>Publications</span></a></li>'."\n";
	      		$tmp_buff .= '      <li><a href="people.html"><span>People</span></a></li>'."\n";
	      		$tmp_buff .= '      <li><a href="history.html"><span>History</span></a></li>'."\n";
	      		$tmp_buff .= '      <li><a href="contrib.html"><span>Contrib</span></a></li>'."\n";
			$tmp_buff .= '      <li><a href="faq.html"><span>FAQ&#160;Page</span></a></li>'."\n";
		
		
      		$tmp_buff .= '      <li><a href="http://gforge.inria.fr/projects/simgrid"><span>SimGrid&#160;Forge</span></a></li>'."\n";
      				
		
      	  	$tmp_buff .= $_;
      	  	$tabs = 0;

	      # Rework the navbar and add menu for use.html
	      # Fix the current "button" of buggy Doxygen tabs  
	      if($file =~ /^html\/use.*/
	      || $file =~ /^html\/installSimgrid.*/
	      || $file =~ /^html\/options.*/ 
	      || $file =~ /^html\/bindings.*/
	      || $file =~ /^html\/gtnets.*/
	      || $file =~ /^html\/ns3.*/
	      || $file =~ /^html\/modules.*/
	      || $file =~ /^html\/annotated.*/)
	      {
				$tmp_buff .= '      <div class="tabs_group_use">'."\n";
				$tmp_buff .= '      	<ul class="tablist">'."\n";
				$tmp_buff .= '        	<li><a href="installSimgrid.html"><span>Install SimGrid</span></a></li>'."\n";
				$tmp_buff .= '        	<li><a href="modules.html"><span>Modules&#160;API</span></a></li>'."\n";
      			$tmp_buff .= '        	<li><a href="annotated.html"><span>Data&#160;Structures</span></a></li>'."\n";
				$tmp_buff .= '        	<li><a href="options.html"><span>Options & configurations</span></a></li>'."\n";
				$tmp_buff .= '        	<li><a href="bindings.html"><span>Bindings</span></a></li>'."\n";
				$tmp_buff .= '        	<li><a href="gtnets.html"><span>GTNets</span></a></li>'."\n";
				$tmp_buff .= '        	<li><a href="ns3.html"><span>NS3</span></a></li>'."\n";
				$tmp_buff .= '      	</ul></div>'."\n";
				$tmp_buff .= '      </div>'."\n";
				
				my $filename = $file;
		        $filename =~ s/html\///g;
		        $filename =~ s/\.html//g;
		        $filename =~ s/publis_.*/publis/g;
		        $tmp_buff =~ s/<li class="current">/<li>/g;
		        $tmp_buff =~ s/<li><a href="$filename.html">/<li class="current"><a href="$filename.html">/g;
		        $tmp_buff =~ s/<li><a href="use.html">/<li class="current"><a href="use.html">/g; 
				
	      }
	
	      # Rework the navbar
	      # Fix the current "button" of buggy Doxygen tabs   
	      if($file =~ /^html\/publis.*/ 
	      || $file =~ /^html\/faq.*/
	      || $file =~ /^html\/people.*/ 
	      || $file =~ /^html\/history.*/ 
	      || $file =~ /^html\/contrib.*/
	      || $file =~ /^html\/pages.*/)
	      {
		      my $filename = $file;
		      $filename =~ s/html\///g;
		      $filename =~ s/\.html//g;
		      $filename =~ s/publis_.*/publis/g;
		      $tmp_buff =~ s/<li class="current">/<li>/g;
		      $tmp_buff =~ s/<li><a href="$filename.html">/<li class="current"><a href="$filename.html">/g;     
	      }
	      

	      print TO $tmp_buff;	      
	      next;
    }
      	
      s|<li><a href="index.html"><span>Main&#160;Page</span>|<li><a href="index.php"><span>Home</span>|g;			
     s|<span>Main&#160;Page</span>|<span>Home</span>|g;	
      s|<span>Modules</span>|<span>Modules&#160;API</span>|g;
      s|<li.*><a href="pages.html"><span>Related&#160;Pages</span></a></li>\n||g;
      s|<li><a href="modules.html"><span>Modules&#160;API</span></a></li>\n||g;
      s|<li><a href="annotated.html"><span>Data&#160;Structures</span></a></li>\n||g;
      s|<li class="current"><a href="modules.html"><span>Modules&#160;API</span></a></li>\n||g;
      s|<li class="current"><a href="annotated.html"><span>Data&#160;Structures</span></a></li>\n||g;
      s|Related Pages<|Documentation&nbsp;Index<|g;
      s|<div id="navrow|<div align="center" id="navrow|g;
      s|<div class="headertitle">|<div class="headertitle" align="center">|g;	
      print TO $_;
    }
    close FROM;
    close TO;
    rename("$outfile", "$file") unless $debug{'rename'};
}



