# Makefile to retrieve and convert pmwiki pages
#

DIRECTIVES := ':cell:\|:cellnr:\|:head:\|:redirect\|:source:\|:source\|:sourceend:\|:tableend:\|:toc:'
NON_NETWORK_PAGES := $(shell ls wiki.d/* | grep -v Network\.)
PM_SAFE_PAGES := $(shell grep -vl "$(DIRECTIVES)" $(NON_NETWORK_PAGES))
MD_SAFE_PAGES := $(patsubst wiki.d/%,%.md,$(PM_SAFE_PAGES))
MD_GROUPED_PAGES := $(subst .,/,$(MD_SAFE_PAGES))
.SECONDARY: $(MD_GROUPED_PAGES)  # don't delete .md files

#GROUPS=$(shell find [A-Z]* -type d)
GROUPS=Car

WIKI := http://markferry.net/pmwiki/pmwiki.php
PMDOWN := ruby ~/src/pmdown/rb/convert_pm2md.rb

# Construct a curl argument list to retrieve all URLs over a single connection
# and output each to a .raw file
CURL_ALL := $(shell echo $(NAMES) | sed -e "s%\S\+%\'$(WIKI)/&?action=markdown\' -o &.md%g")

.PHONY: FORCE help
FORCE: ;

default: help
help:
	echo grep -vl "$(DIRECTIVES)" $(NON_NETWORK_PAGES)

%.md: %.raw  FORCE
	sed -e "s%$(@D)\.%%g" $< \
	| sed -f convert.sed \
	> $@

%.raw:
	mkdir -p $(dir $@)
	curl "$(WIKI)?n=$(subst /,.,$(basename $@))&action=markdown" -o $@

all: $(MD_GROUPED_PAGES)

fix-group-links:
	for g in $(GROUPS); \
	do \
		sed -i -e "s%$$g\.%%g" $$g/*.md ;\
	done