# our self written documents
LYX_FILES := $(shell find -name *.lyx)
# the tex output of lyx
TEX_FILES := $(patsubst %.lyx,%.tex,$(LYX_FILES))
# output files of lyx that are already processed by mod_html_files.py
HTML_FILES := $(patsubst %.lyx,%.html,$(LYX_FILES))
# menue and footers are added later
TARGET_FILES := $(foreach file,$(LYX_FILES),_output/$(basename $(notdir $(file))).html)
# menue and footer files
ASC_FILES := $(wildcard *.asc)
# png files (get converted to eps)
PNG_FILES := $(shell find -name *.png)
# converted eps files
EPS_FILES := $(patsubst %.png,%.eps,$(PNG_FILES))
# look for lyx executable
LYX_BIN = $(shell which lyx lyx-qt lyx-xform | head -1)


# output parameters for latex2html
LATEX2HTMLPREFIX := -no_auto_link -split 0 -no_navigation -no_subdir -dir _output -info 0 -style cryptocd.css -local_icons -address 0


# virtual targets that have different names than the produced files - they will alway be executed,
# if another target depends on them (they do not look for timestamps)
.PHONY : clean clean-targets install all

# default target (offline)
all: $(TARGET_FILES)

# copy the created files to the destination directory (usually outside of this directory tree)
install: $(TARGET_FILES)
	@if [ -z "$(CCD_BUILD_DIR)" ] ; \
		then	echo "CCD_BUILD_DIR must be defined! (this should be done by the parent Makefile)" >&2 ; \
			false ; \
	  fi
	@if [ ! -e "$(CCD_BUILD_DIR)" ] ; \
		then	echo "CCD_BUILD_DIR ($(CCD_BUILD_DIR)) does not exist!" ; \
			false ; \
	  fi
	@cp -r _output/* "$(CCD_BUILD_DIR)/doku"


clean-targets:
	-rm $(TARGET_FILES) 2>/dev/null


# add headers, navigation and footers
$(TARGET_FILES): $(HTML_FILES) $(ASC_FILES)
	cat $(shell find -name $(notdir $@) | grep -v "_output") footer.asc >$@
 
# create tex files from lyx
$(TEX_FILES): menue.inc $(LYX_FILES)
	$(LYX_BIN) -e latex $*.lyx


# original html-files, as they are created by lyx
$(HTML_FILES): %.html: %.tex 
	@-[ ! -e "_output" ] && mkdir _output
	cp menue.inc $(dir $@)
	latex2html $(LATEX2HTMLPREFIX) $*.tex
	rm $(dir $@)/menue.inc
	# die html-Datei wurde jetzt im _output-Verzeichnis erstellt (inklusive Bilder)
	-rm _output/WARNINGS $*-labels.pl $*-internals.pl $*.log 2>/dev/null
	-rm _output/$(notdir $(basename $@)).css 2>/dev/null
	-rm _output/images.aux _output/images.log _output/images.out _output/images.pl _output/images.text _output/img?.old _output/labels.pl _output/missfont.log _output/images.tex 2>/dev/null
	mv _output/$(notdir $(basename $@)).html $@
	python mod_html_files.py $@
	# replace unix-like linebreaks with their DOS couterparts
	unix2dos $@


clean:
	-rm $(TEX_FILES) 2>/dev/null
	-rm $(HTML_FILES) 2>/dev/null
	-rm $(EPS_FILES) 2>/dev/null
	-rm -r _output 2>/dev/null
#	-rm $(foreach dir,$(DOCUMENT_NAMES),$(dir)/menue.inc) 2>/dev/null
#	-rm $(foreach dir,$(DOCUMENT_NAMES),$(dir)/WARNINGS) 2>/dev/null
#	-rm $(foreach dir,$(DOCUMENT_NAMES),$(dir)/$(dir).emergency) 2>/dev/null