#!/usr/bin/env bash
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`
	pandoc --toc --highlight-style=tango -f html instead-manual.html.1 -t latex --template=template.tex  | 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
	pdflatex instead-manual.tex
	pdflatex instead-manual.tex
	pdflatex instead-manual.tex
	rm -f *.toc *.aux *.out *.log
}

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`
	pandoc --toc --highlight-style=tango -f html $mod2 -t latex --template=template.tex | 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
	pdflatex instead-modules.tex
	pdflatex instead-modules.tex
	pdflatex instead-modules.tex
	rm -f *.toc *.aux *.out *.log
}
build_manual
build_modules

