#!/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" stead2
	local d=`date +%d.%m.%y`
	do_pandoc "stead2.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' > "stead2.tex"
	rm -f stead2.html.1
	rm -f *.toc *.aux *.out *.log
	xelatex stead2.tex -o stead2.pdf
	xelatex stead2.tex -o stead2.pdf
	xelatex stead2.tex -o stead2.pdf
	rm -f *.toc *.aux *.out *.log stead2.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' > stead2-modules.tex
	rm -f $mod2
	rm -f *.toc *.aux *.out *.log
	xelatex stead2-modules.tex -o stead2.pdf
	xelatex stead2-modules.tex -o stead2.pdf
	xelatex stead2-modules.tex -o stead2-modules.pdf
	rm -f *.toc *.aux *.out *.log stead2-modules.tex
}
build_manual
build_modules
