#!/usr/bin/perl

use lib "src"; # This be the path where the modules are at
use gencontent;

# Whether to create individual pages for each blog entry, or to cram
# them all in one page.
my $page_separation = 1;
my $page_root = "."; # Put the entry.html files here

# This script finds an anchor from the specified root template HTML file,
# and replaces the anchor with the blog content.
my $root_template = "src/root_template.html";
my $blog_anchor = "BLOGANCHOR";
my $root_output_file = "index.html";

# We also set the title.  For root, it is "", and
# for separate entries, it's " - <description>".
my $title_anchor = "TITLEANCHOR";

open(ROOT_TEMPLATE_FILE, "<$root_template") or die "Couldn't open template file $root_template";
open(OUTPUT_FILE, ">$root_output_file") or die "Couldn't open output file $root_output_file for writing";

# We're using the same root template for individual entries
my $root_content;
if ($page_separation) {
	$root_content = getTOC("null");

	foreach my $entry (@entries) {
		# Rewinding the root file for each entry
		seek(ROOT_TEMPLATE_FILE, 0, 0);

		# Entries start with a TOC where the current entry is not a link
		my $entry_content = getTOC($entry) . "<br/><hr/>\n";
		$entry_content .= getEntryContent($entry);

		my $entry_name = (split("/", $entry))[1];
		open(ENTRY_FILE, ">$page_root/$entry_name.html") or die "Couldn't open entry html $entry_name.html for writing";

		# Extracting the description	
		open(ENTRY_DESC, "<$entry/description") or die "No description file for entry $entry";
		<ENTRY_DESC>; my $desc = <ENTRY_DESC>; chomp $desc;
		
		while (<ROOT_TEMPLATE_FILE>) {
			s/$title_anchor/ - $desc/;
			s/$blog_anchor/$entry_content/;
			print ENTRY_FILE $_;
		}
	}
		
	seek(ROOT_TEMPLATE_FILE, 0, 0);
} else {
	$root_content = getBlogContent();
}

while (<ROOT_TEMPLATE_FILE>) {
	s/$title_anchor//;
	s/$blog_anchor/$root_content/;
	print OUTPUT_FILE $_;
}

exit 0;
