SHELL = /bin/bash

NOMBRE = $(shell grep title montaje.xml | head -1 | cut -d'*' -f2)

todos: epub pdf txt

epub:
	rm -rf formatos/${NOMBRE}.epub
	mkdir -p formatos
	a2x -d book -f epub --xsl-file config/epub.xsl --stylesheet config/epub.css montaje.xml
	mv montaje.epub formatos/${NOMBRE}.epub

pdf:
	rm -rf formatos/${NOMBRE}.pdf
	mkdir -p formatos
	xsltproc -xinclude -o montaje.fo --stringparam double.sided 1 --stringparam ulink.show 0 config/pdf.xsl montaje.xml
	fop -fo montaje.fo -pdf formatos/${NOMBRE}_tmp.pdf
	pdftk A=imgs/portada.pdf B=imgs/blanco.pdf cat A B output formatos/portada_tmp.pdf
	pdftk A=formatos/portada_tmp.pdf B=formatos/${NOMBRE}_tmp.pdf cat A B output formatos/${NOMBRE}.pdf
	rm -rf *.fo formatos/*_tmp.pdf

html:
	rm -rf formatos/${NOMBRE}_html
	mkdir -p formatos/${NOMBRE}_html/imgs
	xmlto -m config/html.xsl --skip-validation -o formatos/${NOMBRE}_html/ html montaje.xml
	for archivo in $$(ls formatos/${NOMBRE}_html/*.html); do sed -i '1 s/^/<!DOCTYPE html>\n/' $$archivo; done
	cp -rf config/html.css formatos/${NOMBRE}_html/estilo.css
	cp -rf imgs formatos/${NOMBRE}_html/
	rm -f formatos/${NOMBRE}_html/*.proc
	rm -f formatos/${NOMBRE}_html/imgs/portada.*
	rm -f formatos/${NOMBRE}_html/imgs/blanco.*

txt: html
	rm -rf formatos/${NOMBRE}.txt
	mkdir -p formatos
	w3m -dump formatos/${NOMBRE}_html/index.html > formatos/obra.txt
	w3m -dump formatos/${NOMBRE}_html/pr*.html  >> formatos/obra.txt
	w3m -dump formatos/${NOMBRE}_html/ch*.html  >> formatos/obra.txt
	w3m -dump formatos/${NOMBRE}_html/bi*.html  >> formatos/obra.txt
	w3m -dump formatos/${NOMBRE}_html/ap*.html  >> formatos/obra.txt
	sed -e '/Anterior/,+2d' formatos/obra.txt > formatos/${NOMBRE}.txt
	sed -e '/Siguiente/,+1d' formatos/${NOMBRE}.txt > formatos/obra.txt
	sed '/Fecha/d' formatos/obra.txt > formatos/${NOMBRE}.txt
	sed -i 's/ / /g' formatos/${NOMBRE}.txt
	rm -f formatos/obra.txt
