#!/usr/bin/env bash
function do_pandoc()
{
	pandoc --toc --highlight-style=tango -f html $@ -t latex --latex-engine=xelatex  -V sansfont="Verdana" -V mainfont="Verdana" -V monofont="Liberation Mono" --variable fontsize=12pt --template=template.tex -V documentclass=extarticle
}

function build_html()
{
	wget "http://instead.syscall.ru/wiki/doku.php?id=$1&do=export_xhtml" -O "$2".html.1
	cat "$2.html.1" | awk 'BEGIN {
			toc = 0;
			wrap=0
		}
		{
			if ($0 ~ "<!-- TOC START -->") {
				toc=1;
			} else if ($0 ~ "<!-- TOC END -->") {
				toc=0;
			}
#			if (wrap == 1 && $0 ~ "^</div>") {
#				wrap=-1
#				print "WRAPCENTERMAGICEND"
#			} 
#			if ($0 ~ "<div class=\"wrap_center") {
#				wrap=-2
#				print "WRAPCENTERMAGICSTART"
#			}
			if (toc == 0 && wrap >= 0) {
				print;
			}
#			if (wrap == -1) { wrap = 0 };
#			if (wrap == -2) { wrap = 1 };
		}' > "$2.html.2";
	mv -f "$2.html.2" "$2.html.1"
#	cp "$2.html.1" "$2.html.z"
}

function build_manual()
{
	build_html "ru:gamedev:documentation" instead-manual
	local d=`date +%d.%m.%y`
	do_pandoc "instead-manual.html.1" | sed -e 's/\\date{}/\\date{'$d'}/' -e 's/\\author{}/\\author{Петр Косых}/' -e 's/{\\char13}/'"'"'/g' -e 's/ //g' -e 's/\\title{.*}/\\title{Руководство INSTEAD}/' -e 's/WRAPCENTERMAGICSTART/\\begin{Info}/g' -e 's/WRAPCENTERMAGICEND/\\end{Info}/g' > "instead-manual.tex"
	rm -f instead-manual.html.1
	rm -f *.toc *.aux *.out *.log
	xelatex instead-manual.tex -o instead-manual.pdf
	xelatex instead-manual.tex -o instead-manual.pdf
	xelatex instead-manual.tex -o instead-manual.pdf
	rm -f *.toc *.aux *.out *.log instead-manual.tex
}

function build_modules()
{
	local mod="click format hideinv kbd  prefs timer xact sprites sound nouse counters wroom nolife proxymenu dash hotkeys para quotes theme snapshots dbg trigger keyboard cutscene fonts"
	local mod2=""
	for m in $mod; do
		build_html ru:gamedev:modules:$m $m #--template=template.tex
		mod2="$mod2$m.html.1 "
	done
	local d=`date +%d.%m.%y`
	do_pandoc $mod2 | sed -e 's/ //g' | awk 'BEGIN {
			scr = 0;
		}
		{
			if ($0 ~ "\subsection{Скриншоты}") {
				scr=1;
			} else if (scr == 1 && $0 ~ "\end{document}" ) {
				scr=0
			} else if (scr == 1 && ($0 ~ "\section" || $0 ~ "\subsection") ) {
				scr=0;
			}
			if (scr == 0) {
				print;
			}
		}' | sed -e 's/\\date{}/\\date{'$d'}/' -e 's/\\title{.*}/\\title{Модули INSTEAD}/' -e 's/{\\char13}/'"'"'/g'  -e 's/WRAPCENTERMAGICSTART/\\begin{Info}/g' -e 's/WRAPCENTERMAGICEND/\\end{Info}/g' > instead-modules.tex
	rm -f $mod2
	rm -f *.toc *.aux *.out *.log
	xelatex instead-modules.tex -o instead-manual.pdf
	xelatex instead-modules.tex -o instead-manual.pdf
	xelatex instead-modules.tex -o instead-modules.pdf
	rm -f *.toc *.aux *.out *.log instead-modules.tex
}
build_manual
build_modules
