#! /usr/bin/perl
#
# Last modification: Mon, 28 Oct 1996 08:56:04 +0200
#
# j_mkhtml  - Copyright (c)1996 by Fabrizio Polacco <fpolacco@debian.org>.
# All rights reserved.  This program is free software; you can redistribute it
# and/or modify it under the same terms as Perl itself.

# This script is intended to be used to build the debian package of the html
# on-line magazine Pluto Journal, but can be used to easily build also other
# online magazines.

# Usage: j_mkhtml <source-dir> <dest-dir>
# the script executes in the source dir where there are:
# "html.wrapper", "html.list", one "<file>.body" for each "<file>.html" listed
# in the "html.list" file.

# This script reads the file "html.list" and builds a list of values from its
# contents; then for each filename listed it processes the file "html.wrapper"
# copying the output to <dest-dir>/<filename>.html The process consists in
# executing special commands and substituting special variables.

# Special commands are:

#	@@!include <filename>@@	substitute the command string with the content
#				of <filename>
#	@@!include BODY @@	substitute the command string with the content
#				of current <@@filename@@>.body
#	@@!erase @@		don't copy this line to dest file (the line is
#				not processed and other commands will be ignored)

# The variables are:
#	@@filename@@	the name of the file in the list, without extension
#	@@prev-name@@	the filename of the previous row.
#	@@next-name@@	the filename of the next row.
#	@@index-name@@	the filename of the index file, usually "../index."
#	@@title@@	the string to be used in the <title> tag
#	@@heading@@	the string to appear in large font on top of the page
#	@@type@@	the type of the page, to appear on top and foot
#	@@alt@@		the string to be used within square brackets as 
#			ALT attribute in IMG links that points to this page
#	@@prev-alt@@	the ALT attribute string of the previous page
#	@@next-alt@@	the ALT attribute string of the next page
#	@@index-alt@@	the ALT attribute string of the index page

# the first file in the list is considered the INDEX row, a special case, whose
# contents are used as the "prev" values for the first file (the row after this
# one) and as the "next" for the last value.

# index file itself is considered being outside of this process, with directs
# links to the files in the dest-dir.
#

# needs require libwww-perl to compile package
use HTML::Entities %char2entity;

sub process_file
{
	local( *IN, $file, $remain ); ($IN) = @_;	# my() can't use filehandles
	open(IN, $IN) or die "Cannot open input file $IN\n";
	while ( <IN> )
	{
		next if ( /\@\@!erase\s*\@\@/io );
		s/\@\@index-name\@\@/${list[0][0]}/gio;
		s/\@\@index-alt\@\@/${list[0][1]}/gio;
		s/\@\@heading\@\@/${list[0][2]}/gio;

		s/\@\@filename\@\@/${list[$j][0]}/gio;
		s/\@\@prev-name\@\@/${list[$j-1][0]}/gio;
		s/\@\@next-name\@\@/${list[$j+1][0]}/gio;

		s/\@\@alt\@\@/${list[$j][1]}/gio;
		s/\@\@prev-alt\@\@/${list[$j-1][1]}/gio;
		s/\@\@next-alt\@\@/${list[$j+1][1]}/gio;

		s/\@\@title\@\@/${list[$j][2]}/gio;
		s/\@\@type\@\@/${list[$j][3]}/gio;
# patch per generare l'indice
		s/\@\@nomefile\@\@/${indexlist[$j][1]}/gio;
		s/\@\@titoloarticolo\@\@/${indexlist[$j][3]}/gio;
		s/\@\@nomerubrica\@\@/${indexlist[$j][4]}/gio;
		s/\@\@nomeautore\@\@/${indexlist[$j][5]}/gio;
		s/\@\@mailautore\@\@/${indexlist[$j][6]}/gio;
		s/\@\@issue\@\@/${indexlist[0][3]}/gio;
		s/\@\@issuelong\@\@/${indexlist[0][4]}/gio;
		$numeroriga=$j+1;
		s/\@\@numeroriga\@\@/$numeroriga/gio;
		$numerorighe=$#indexlist+1;
		s/\@\@numerorighe\@\@/$numerorighe/gio;
# fine patch

		s/([\200-\377])/$HTML::Entities::char2entity{$1}/go;
        if ( s/\@\@!include\s*([-\w\.]+)\s*\@\@/\@\@/gio )
		{
			$file = (($1 =~ /^BODY$/io) ? ${list[$j][0]} : $1);
			$file =~ s/html$/body/o ;
			$idx = index($_,"@@");
			print substr( $_, $[, $idx) if ($idx > $[);
			$remain = substr( $_, $idx+2);	# to be printed later
			&process_file( $file);
			print OUT $remain;
		}else{
			print OUT ;
		}
	}
	close IN;
}
sub create_index()
{
open( OUT, "> indice") or die "Cannot open output file \n";
 				for $j ( 2 .. ($#indexlist) )
				{	 
					next if ${indexlist[$j][0]} eq "I";
					if (${indexlist[$j][0]} eq "R")
					{ # debug print "è la rubrica " . ${indexlist[$j][4]} . "\n";
						$file="idxrubrica.token";
						&process_file($file);
					}else{
						${indexlist[$j][1]} .= "html" if (${indexlist[$j][1]} =~ /\.$/o);
						# debug print "è il file  " . ${indexlist[$j][1]}. "\n";
						$file="index.token";
						&process_file($file);
					}
					print OUT;
				}
close OUT;
		
}


sub slurp_list
{
	open( IN, "< html.list") or die "Cannot open html.list\n";
	$j = $[; while ( <IN> )				# $[ contiene il valore del primo indice
										# di un array - default 0
	{
	
		chomp;							# elimina \n alla fine della riga
		s/[ \t]*#.*//o; 				# elimina i commenti
		tr/\t//s;						# elimina le doppie tabulazioni

		next if ( $_ eq ""); 			# va avanti se a questo punto abbiamo una
										# stringa nulla
		push @list,  [split(/\t/)] ;	# genera un array bidimensionale inserendo 
										# in @list il riferimento ad un 
										# array anonimo che contiene i valori
										# splittati da $_  usando \t come separatore
		${list[$j][0]} .= "html" if (${list[$j][0]} =~ /\.$/o);
		$j++;
	}
		close IN;
	# adds name anchor to link to index
	${list[0][0]} .= "#${list[0][2]}" if ${list[0][2]};
	# new row to point forward to index
	
	push @list, [ (${list[0][0]},${list[0][1]}) ];
	
}
# patch per generare l'indice
sub slurp_index_list
{
	open( IN, "< index.list") or die "Cannot open index.list\n";
	$j = $[; while ( <IN> )				# $[ contiene il valore del primo indice
										# di un array - default 0
	{
	
		chomp;								# elimina \n alla fine della riga
		s/[ \t]*#.*//o; 					# elimina i commenti
		tr/\t//s;							# elimina le doppie tabulazioni
		next if ( $_ eq ""); 				# va avanti se a questo punto abbiamo una
											# stringa nulla
		push @indexlist,  [split(/\t/)] ;	# genera un array bidimensionale inserendo 
											# in @list il riferimento ad un 
											# array anonimo che contiene i valori
											# splittati da $_  usando \t come separatore
		
# 	${indexlist[$j][0]} può essere I per Indice R per Rubrica o A per Articolo
#	
			$j++;
	}
	for $j ( 0 .. ($#indexlist) )
	{
	
		for $k(1 .. 6)
	{
		# inserisce un "#" per "commentare" le riga con i nomi delle rubriche
		${htmllist[$j][0]} = "#" if ${indexlist[$j][0]} eq "R";
			
		${htmllist[$j][$k-1]} = ${indexlist[$j][$k]};
		}
	
	}
	open( LIST, "> html.list") or die "Cannot open output file ${filename}\n";
	for $j ( 0 .. ($#htmllist) )
	{
		for $k(0 .. 5)
	{
			print LIST ${htmllist[$j][$k]}."\t";
	}
	print LIST "\n";
}
	close LIST;

	close IN;
}


# script starts here
my $oldpwd = `pwd`;
my $source_dir = ".";
my $dest_dir = "/tmp";
$source_dir = $ARGV[0] if scalar(@ARGV) == 2;
$dest_dir = $ARGV[1] if scalar(@ARGV) == 2;
$dest_dir = $ARGV[0] if scalar(@ARGV) == 1;

chdir $source_dir or die "Cannot chdir to $source_dir: $!\n";
die "Destination dir $dest_dir doesn't exist\n" if ! -d $dest_dir;
&slurp_index_list;
&create_index;
open( OUT, "> index.body") or die "Cannot open output file \n";
&process_file("index.wrapper");
close OUT;
# fine aggiunta giampa

&slurp_list;
for $j ( 1 .. ($#list - 1) )	# first and last rows point to index
{	
	$filename = "${dest_dir}/$list[$j][0]"; 	# genera il nome completo del file
												# da aprire in scrittura 
	open( OUT, "> ${filename}") or die "Cannot open output file ${filename}\n";
	
		&process_file( "html.wrapper");

	close OUT;
}
END { chdir $oldpwd; }
