<?php

// This is pretty bad code. Sorry. I will clean it up.

foreach (glob("configs/*.php") as $config_file) {
	if (is_file($config_file)) {
		echo "Processing render configuration $config_file\n";
		render_with_config_path($config_file);
	}
	
}

function render_with_config_path($config_file) {
	$config = array();
	include($config_file);
	
	if (!isset($config["pages"])) {
		echo "Not a valid configuration; skipping\n";
		return;
	}

	// Prepare substitutions
	$substitutions = array("{TITLE}" => $config["title"]);
	
	$rev_id = exec("git rev-parse --short HEAD", $output, $retval);
	if ($retval != 0) {
		$rev_id = "unknown";
	}
	$substitutions["{GIT_REV_ID}"] = $rev_id;
	date_default_timezone_set('UTC');
	$substitutions["{TIMESTAMP}"] = date("Y-m-d H:i:s e");
	
	
	// Copy resources across
	$resources_to_copy = array_merge(glob("resources/common/*"), glob($config["resources_dir"] . "/*"));
	$res_out_dir = $config["output_dir"] . "/" . $config["resources_output_dir"];
	
	if (!is_dir($res_out_dir)) {
		mkdir($res_out_dir, 0777, true);
	}
	foreach ($resources_to_copy as $res) {
		$res_name = basename($res);
		$substitutions["{RES:$res_name}"] = $config["resources_output_dir"] . "/$res_name";
		copy($res, "$res_out_dir/$res_name");
	}
	
	if (!is_dir($config["output_dir"])) {
		mkdir($config["output_dir"], 0777, true);
	}
	
	// We need to pre-process all the pages to get the section headings ready
	$sections = array(); // entries are associative arrays
	$template_texts = array();
	$page_no = 1;
	foreach ($config["pages"] as $page) {
		// Read in the text
		$template_html = $config["html_dir"] . "/" . $page["id"] . ".html";
		$text = file_get_contents($template_html);
		
		$section_no = 0;
		$subsection_no = 0;
		
		// Look for things we need to convert to h1, h2, h3
		preg_match_all("/{HEADING:(PAGE|SECTION|SUBSECTION):([^:]*):([^}]+)}/", $text, $section_matches);
		$originals = $section_matches[0];
		$types = $section_matches[1];
		$ids = $section_matches[2];
		$titles = $section_matches[3];
		
		// TOC gets its info from the config file, not from an h1 which may or may not be present
		$page_id = $page["id"];
		$sections[] = array("type" => "PAGE", "page" => "$page_id.html", "section" => "", "number" => "$page_no.", "title" => $page["title"]);
		$page_title = $page["title"];
		$substitutions["{LINK:$page_id}"] = "<a href=\"$page_id.html\">$page_title</a>";
		
		for ($i = 0; $i < count($types); $i++) {
			$tag = "h1";
			$number = "$page_no.";
			if ($types[$i] == "SECTION") {
				$tag = "h2";
				$section_no++;
				$subsection_no = 0;
				$number = "$page_no.$section_no.";
			}
			if ($types[$i] == "SUBSECTION") {
				$tag = "h3";
				$subsection_no++;
				$number = "$page_no.$section_no.$subsection_no.";
			}
			
			// If we have an ID
			$anchor_start = "";
			$anchor_end = "";
			if (strlen($ids[$i]) > 0 && $types[$i] != "PAGE") { // pages are always added the TOC and have empty section_id
				// Add it to the TOC array
				$sections[] = array("type" => $types[$i], "page" => "$page_id.html", "section" => $ids[$i], "number" => $number, "title" => $titles[$i]);
				// Also create an internal anchor
				$anchor_start = "<a name=\"$ids[$i]\">";
				$anchor_end = "</a>";
			}
			
			$final_tag = "<$tag>$anchor_start$number $titles[$i]$anchor_end</$tag>";
			
			// Replace the template with the tag
			$text = str_replace($originals[$i], $final_tag, $text);
			
			// Now create substitutions for this tag so other pages can refer to them
			$page_id = $page["id"];
			$section_id = $ids[$i];
			$title = $titles[$i];
			$substitutions["{LINK:$section_id}"] = "<a href=\"$page_id.html#$section_id\">$title</a>";
			$substitutions["{TITLE:$section_id}"] = $title;
		}
		
		// Save the text for later
		$template_texts[$page["id"]] = $text;
		$page_no++;
	}
	
	// Render each page
	for ($i = 0; $i < count($config["pages"]); $i++) {
		$page = $config["pages"][$i];
		
		// Configure page-specific substitutions
		$substitutions["{PREV_URL}"] = "";
		$substitutions["{PREV_TITLE}"] = "";
		$substitutions["{NEXT_URL}"] = "";
		$substitutions["{NEXT_TITLE}"] = "";
		$substitutions["{TOC_URL}"] = "index.html";
		$substitutions["{TOC_TITLE}"] = "Contents";
		$substitutions["{PAGE_TITLE}"] = $page["title"];
		
		if (isset($config["pages"][$i-1])) {
			$prev_page = $config["pages"][$i-1];
			$substitutions["{PREV_URL}"] = $prev_page["id"] . ".html";
			$substitutions["{PREV_TITLE}"] = $prev_page["title"];
		}
		if (isset($config["pages"][$i+1])) {
			$next_page = $config["pages"][$i+1];
			$substitutions["{NEXT_URL}"] = $next_page["id"] . ".html";
			$substitutions["{NEXT_TITLE}"] = $next_page["title"];
		}
		
		
		$template_html = $config["html_dir"] . "/" . $page["id"] . ".html";
		$out_html = $config["output_dir"] . "/" . $page["id"] . ".html";
		
		if (is_file($out_html)) {
			unlink($out_html);
		}
		
		append_file_and_sub($out_html, "html/common/header.html", $substitutions);
		$text = do_substitutions($template_texts[$page["id"]], $substitutions);
		file_put_contents($out_html, $text, FILE_APPEND);
		append_file_and_sub($out_html, "html/common/footer.html", $substitutions);
	}
	
	// Render the index / TOC now that we have all the information at hand
	$toc_html = $config["output_dir"] . "/index.html";
	$toc_text = file_get_contents("html/common/toc.html");
	$toc_h1 = file_get_contents("html/common/toc-h1.html");
	$toc_h2 = file_get_contents("html/common/toc-h2.html");
	$toc_h3 = file_get_contents("html/common/toc-h3.html");
	
	foreach ($sections as $section) {
		$start = $toc_h1;
		if ($section["type"] == "SECTION") $start = $toc_h2;
		if ($section["type"] == "SUBSECTION") $start = $toc_h3;
		
		$toc_subs["{TOC_ENTRY_NUMBER}"] = $section["number"];
		$toc_subs["{TOC_ENTRY_TITLE}"] = $section["title"];
		$toc_subs["{TOC_ENTRY_PAGE}"] = $section["page"];
		$toc_subs["{TOC_ENTRY_SECTION}"] = $section["section"];
		
		$line = do_substitutions($start, $toc_subs);
		$toc_text .= "$line\n";
	}
	
	$substitutions["{PREV_URL}"] = "";
	$substitutions["{PREV_TITLE}"] = "";
	$substitutions["{NEXT_URL}"] = $config["pages"][0]["id"] . ".html";
	$substitutions["{NEXT_TITLE}"] = $config["pages"][0]["title"];
	$substitutions["{PAGE_TITLE}"] = "Contents";
	
	// Write it to disk
	if (is_file($toc_html)) {
		unlink($toc_html);
	}
	append_file_and_sub($toc_html, "html/common/header.html", $substitutions);
	file_put_contents($toc_html, $toc_text, FILE_APPEND);
	append_file_and_sub($toc_html, "html/common/footer.html", $substitutions);
	
	// This manual is all done
	echo "Manual '" . $config["title"] . "' completed rendering at: " . $config["output_dir"] . "\n\n";
}

function append_file_and_sub($dest, $src, $substitutions) {
	// Read in starting text
	$text = file_get_contents($src);
	
	$text = do_substitutions($text, $substitutions);
	
	// Append processed text to the destination file
	touch($dest);
	file_put_contents($dest, $text, FILE_APPEND);
}


function do_substitutions($text, $substitutions) {
	// Perform all template substitutions
	foreach ($substitutions as $from => $to) {
		$text = str_replace($from, $to, $text);
	}
	
	return $text;
}



?>