#!/usr/bin/perl -w
#
# Bacula Systems - Philippe Chauvat
# 27 jul 2012
#
# This script is designed to translate Bacula enterprise LaTeX2HTML
# documentation files to something more "tunable" / "adaptable" from a CSS
# point of view.
#
# $1 is an HTML file to analyze and translate
# The output is automatically send to $1.out
#
# - add some ids, class
# - re-order some piece of HTML code
#
# This script is based on HTML::Parser module
#
# args:
# -i: HTML input file
# -o: HTML output file
# -j: javascript directory
# -c: css directory
# -p: images (pictures) directory
# -n: Manual name
# -r: Source directory (ako part of -i arg)
# -?: help / usage
# -d: debug requested
use HTML::Parser ;
use HTML::TreeBuilder ;
use HTML::PullParser ;
use Getopt::Long ;
use File::Basename ;
use Data::Dumper ;
sub usage {
    print "translatedoc.pl -i | --input html-source-file
 [ -o | --output html-destination-file ]
 [ -j | --javascript javascript-diretory ]
 [ -c | --css css-directory ]
 [ -p | --pictures pictures-directory ]
 [ -n | --name manual_name ]
 [ -d | --debug ]
 [ -r | --source-directory the_original_root_directory ]
 [ --help | -? ]\n" ;
    exit 1 ;
}
#
# Send message to output in case of debug only
# ======================
sub debugdump {
    my ($what,$msg) = @_ ;
    if ($debug) {
	print "\n===============================\nBegin of $msg\n" ;
	$what->dump ;
	print "\n===============================\nEnd of $msg\n\n" ;
    }
}
#
# Args to Vars
our($inputfile,$outputfile,$help,$debug,$mytree,$extractmenu,$picturesdir,
    $cssdir,$javascriptdir,$manualname,$sourcedir) ;
#
# Usage in case of missing arguments
usage() unless($#ARGV > -1) ;
#
# Input file / Output file
GetOptions("input|i=s" => \$inputfile,
	   "output|o=s" => \$outputfile,
	   "pictures|p=s" => \$picturesdir,
	   "css|c=s" => \$cssdir,
	   "source-directory|r=s" => \$sourcedir,
	   "javascript|j=s" => \$javascriptdir,
	   "name|n=s" => \$manualname,
	   "debug|d" => \$debug,
	   "help|?" => \$help) or usage() ;
usage() if ($help) ;
usage() unless (defined $inputfile) ;

die "$inputfile does not exists.\n" unless -e $inputfile ;

if (! defined $outputfile ) {
    $outputfile = "./" . basename($inputfile) . ".out" ;
}

if (! defined $picturesdir ) {
    $picturesdir = "../images" ;
}

if (! defined $cssdir ) {
    $cssdir = "../css" ;
}

if (! defined $javascriptdir ) {
    $javascriptdir = "../js" ;
}
if (! defined $manualname) {
    $manualname = "main" ;
}
#
# Build HTML Tree of existing page
$mytree = HTML::TreeBuilder->new ;
$mytree->parse_file($inputfile) ;
debugdump($mytree,"E1: ") ;
#
# Find the beginning of the content
# Which is also a point where to put
# the menu
$beginning_of_content = $mytree->look_down('_tag','h1') ;
$beginning_of_content = $mytree->look_down('_tag','h2') unless ($beginning_of_content) ;
die "The only thing we could test is a <H1> / <H2> tags, which does not exist there...:$!\n"  unless($beginning_of_content) ;
#
# Remove every 'dirty' lines
# between <body> and <h1> tag
# What is "before" the <h1> tag (between <body> and <h1>) is just dropped
# my @lefts = $beginning_of_content->left() ;
# foreach my $l (@lefts) {
#     $l->detach_content() ;
#     $l->delete_content() ;
#     $l->detach() ;
#     $l->delete() ;
# }
# #
# # Remove Bacula community logo
# if ($childlinks = $beginning_of_content->look_down('_tag','img','alt','\\includegraphics{bacula-logo.eps}')) {
#     $childlinks->detach() ;
#     $childlinks->delete() ;
# }
# # End remove Bacula logo
# #
# # Remove 'address' tag
# if ($childlinks = $mytree->look_down('_tag','address')) {
#     $childlinks->detach() ;
#     $childlinks->delete() ;
# }
# # End remove address
#
# End remove dirty lines
#
# Replace textregistered images with the HTML special char
my @images = $mytree->look_down('_tag','img') ;
foreach $childlinks (@images) {
    my $alttext = $childlinks->attr('alt') ;
#    print "Alt: $alttext\n" ;
    if ($alttext =~ /.*registe.*/) {
	$childlinks->preinsert(HTML::Element->new_from_lol(['span', {'class' => 'expochar' }, '&reg;'])) ;
	$childlinks->detach() ;
	$childlinks->delete() ;
    }
    if ($alttext =~ /.*bacula.*-logo.*/) {
	$childlinks->detach() ;
	$childlinks->delete() ;
    }
}
@images = $mytree->look_down('_tag','img') ;
foreach $childlinks (@images) {
    my $img = $childlinks->attr('src') ;
    if ($img =~ /^\.\//) {
	$img =~ s/\.\/// ;
	$img = $picturesdir . '/' . $img ;
	$childlinks->attr('src',$img) ;
#	print "img: " . $img . "\n" ;
    }
}
if ($childlinks = $mytree->look_down('_tag','title')) {
    # foreach my $i ($childlinks->content_refs_list) {
    # 	next if ref $$i ;
    # 	print "contenu: " . $$i . "\n" ;
    # }
    $childlinks->postinsert(HTML::Element->new_from_lol(['meta',{ 'http-equiv' => 'content-type', 'content' => 'text/html; charset=iso-8859-1' } ])) ;
}
if ($childlinks = $mytree->look_down('_tag', 'div','class','author_info')) {
    $childlinks->preinsert(
	HTML::Element->new_from_lol(
	    [ 'h1', { 'align' => 'center' },
	      [ 'div', { 'align' => 'center' },
		[ 'big', { 'class' => 'LARGE' }, "The Leading Open Source Backup Solution" ]
	      ]
	    ]
	)) ;
#
# Adding the logo
    if (my @regs = $mytree->look_down('_tag', 'span','class','MATH')) {
	foreach $childlinks (@regs) {
	    $childlinks->preinsert(HTML::Element->new_from_lol(['span', {'class' => 'expochar' }, '&reg;'])) ;
	    $childlinks->detach() ;
	    $childlinks->delete() ;
	}
	if ($childlinks = $mytree->look_down('_tag', 'div','class','navigation')) {
	    $childlinks->postinsert(
		HTML::Element->new_from_lol(
		    [ 'div', {'align' => 'center'} ,
		      [ 'img', { 'src' => $picturesdir . '/borg-logo.png', 'id' => 'borg_logo','alt' => 'Bacula Community Logo' }]
		    ]
		)) ;
	}
    }
}
#
# Manage css to be located into ../css
my @links = $mytree->look_down('_tag','link') ;
foreach $childlinks (@links) {
    my $link = $childlinks->attr('href') ;
    if ($link =~ /^[a-zA-Z]+\.css/) {
	$link = $cssdir . '/' . $link ;
	$childlinks->attr('href',$link) ;
    }
}
#
# Manage navigation
my @navs = $mytree->look_down('_tag','div','class','navigation') ;
foreach my $nav (@navs) {
    my @imgs = $nav->look_down('_tag','img') ;
    foreach $childlinks (@imgs) {
#	print "Traitement des images de navigation...\n" ;
	my $img = $childlinks->attr('src') ;
	if ($img =~ /^next.+/) {
	    $childlinks->attr('class','navigation-next') ;
	    $childlinks->attr('src', $picturesdir . '/' . $img) ;
	}
	if ($img =~ /^index.+/) {
	    $childlinks->attr('class','navigation-next') ;
	    $childlinks->attr('src', $picturesdir . '/' . $img) ;
	}
	if ($img =~ /^content.+/) {
	    $childlinks->attr('class','navigation-next') ;
	    $childlinks->attr('src', $picturesdir . '/' . $img) ;
	}
	if ($img =~ /^prev.+/) {
	    $childlinks->attr('class','navigation-prev') ;
	    $childlinks->attr('src', $picturesdir . '/' . $img) ;
	}
	if ($img =~ /^up.+/) {
	    $childlinks->attr('class','navigation-up') ;
	    $childlinks->attr('src', $picturesdir . '/' . $img) ;
	}
    }
}
#
# Locate all <a name="whatever_but_SECTION...">
my @atags = $mytree->look_down('_tag','a') ;
local *AFH ;
open AFH, ">> list-of-anchors" or die "Unable to append to list-of-anchors file\n"; 
foreach $childlinks (@atags) {
    my $atagname ;
    if ($atagname = $childlinks->attr('name')) {
	print AFH $manualname . "\t" . basename($inputfile) . "\t" . $atagname . "\n" ;
    }
}
close AFH ;
#
# Send the tree to an HTML file
if ($outputfile) {
    local *FH ;
    open FH, ">" . $outputfile or die "Unable to create $outputfile: $!\n" ;
    print FH $mytree->as_HTML("<>","\t",{}) ;
    close FH ;
}
else {
    print $mytree->as_HTML("","\t",{}) ;
}

1;
