#setup command tools
TOPDIR := $(CURDIR)
ESCAPE_TOPDIR = $(subst /,\/,$(TOPDIR))
MAKEFILE_TEMPLATE := $(TOPDIR)/Makefile
LH := leohtml -ew
H := $(wildcard *.lhhtml)
#objs := $(patsubst index.html,,$(patsubst %.lhtml,%.html,$(wildcard *.lhtml)))
objs := $(patsubst %.lhtml,%.html,$(wildcard *.lhtml))
html_objs := $(patsubst %.lhtml,html/%.html,$(wildcard *.lhtml))
subdirs := $(notdir $(subst .,,$(shell find . -maxdepth 1 -type d -o \( -type l -a -type d \))))
sub_makefiles := $(patsubst %,%/Makefile,$(subdirs))

#available commands
doit: all

showvar:
	@echo '$$(TMP) =' $(TMP)
	@echo '$$(MAKEFILE_TEMPLATE) =' $(MAKEFILE_TEMPLATE)
	@echo '$$(LH) =' $(LH)
	@echo '$$(subdirs) =' $(subdirs)
	@echo '$$(sub_makefiles) =' $(sub_makefiles)
	@echo '$$(objs) =' $(objs)
	@echo '$$(html_objs) =' $(html_objs)

$(MAKEFILE_TEMPLATE): ;

force: ;

vim:
	cd ~ && tar zcf /tmp/vim-config.tar.gz .vim .vimrc && cd - && mv /tmp/vim-config.tar.gz . && chmod a+r vim-config.tar.gz

dist:
	@echo "packaging public_html to /tmp/public_html.tar.gz..."
	cd ~ && tar zcf /tmp/public_html.tar.gz public_html -h

update_makefile: $(sub_makefiles)
	@for dir in $(subdirs); do\
		$(MAKE) -C $$dir update_makefile; \
		done
#update subdirs' Makefile automatically
$(sub_makefiles): $(MAKEFILE_TEMPLATE)
	cat $(MAKEFILE_TEMPLATE) | sed -e "1,10s/\$$(TOPDIR)/$(ESCAPE_TOPDIR)/g" > $@

#all: update_makefile $(objs) force
all: $(objs) force 


clean:
	#@for dir in $(subdirs); do\
		$(MAKE) -C $$dir clean; \
		done
	rm -f $(objs)

#set up rules
$(objs):%.html:%.lhtml $(H)
	@-chmod u+w $@ 
	$(LH) -if $< -of $@ 
	@chmod ug+r $@ 
	@chmod aug-w $@ 

$(html_objs):html/%.html:%.lhtml $(H)
	@-chmod u+w $@ 
	$(LH) -if $< -of $@ 
	@chmod ug+r $@ 
	@chmod aug-w $@ 
#the server require index.htm as default page
index.htm: index.lhtml $(H)
	@-chmod u+w $@ 
	$(LH) -if $< -of $@
	@chmod aug-w $@ 
