PKGS := symantic-grammar symantic-document symantic symantic-lib symantic-cli
HS := $(shell find $(PKGS) -name '*.hs' -not -name 'HLint.hs')

all: build

build: $(PKGS:=/build)
%/build:
	cd $*; stack $(STACK_FLAGS) build $(STACK_BUILD_FLAGS)
.PHONY: $(PKGS) $(foreach p,$(PKGS),$(eval $p: $p/build))

.PHONY: $(PKGS:=/test)
test: $(PKGS:=/test)
define test
$p/test:
	! grep -q '^Test-Suite\>' $p/$p.cabal || \
	{ cd $p; stack $$(STACK_FLAGS) test $$(STACK_TEST_FLAGS); }
endef
$(foreach p,$(PKGS),$(eval $(call test)))

clean:   $(PKGS:=/clean)
cleaner: $(PKGS:=/cleaner)
%/clean:
	cd $*; stack $(STACK_FLAGS) clean $(STACK_CLEAN_FLAGS)
%/cleaner:
	cd $*; stack $(STACK_FLAGS) clean --full $(STACK_CLEAN_FLAGS)

%/fast: override STACK_BUILD_FLAGS+=--fast
%/fast: override STACK_HADDOCK_FLAGS+=--fast
%/fast: override STACK_TEST_FLAGS+=--fast
%/fast: %
	

doc: $(PKGS:=/doc)
%/doc:
	cd $*; stack $(STACK_FLAGS) haddock $(STACK_HADDOCK_FLAGS)
%.html: %.md
	markdown $*.md >$*.html
%.html/view: %.html
	sensible-browser $*.html

HLint.hs: $(HS)
	sed -i -e '/^-- BEGIN: generated hints/,/^-- END: Generated by hlint/d' HLint.hs
	echo '-- BEGIN: generated hints' >> HLint.hs
	hlint $(foreach p,$(PKGS),--find $p) | grep '^'infix | sort -u >> HLint.hs
	echo '-- END: generated hints' >> HLint.hs

lint: $(PKGS:=/lint) $(HS)
%/lint: HLint.hs
	cd $*; if hlint --quiet --report=hlint.html -XNoCPP \
	 $(shell cabal-cargs --format=ghc --only=default_extensions --sourcefile=$*) $(HLINT_FLAGS) .; \
	then rm -f hlint.html; \
	else sensible-browser ./hlint.html & fi

tag: $(PKGS:=/tag)
%/tag:
	cabal=$*/$*.cabal; \
	name=$$(sed -ne 's/^name: *\(.*\)/\1/p' "$$cabal"); \
	version=$$(sed -ne 's/^version: *\(.*\)/\1/p' "$$cabal"); \
	git tag --merged | grep -Fqx "$$name-$$version" || \
	git tag -f -s -m "$$name v$$version" $$name-$$version

tar: $(PKGS:=/tar)
%/tar:
	cd $*; stack $(STACK_FLAGS) sdist $(STACK_SDIST_FLAGS)
upload: $(PKGS:=/upload)
%/upload:
	cd $*; LANG=C stack $(STACK_FLAGS) upload $(STACK_UPLOAD_FLAGS) .

.PHONY: stats
stats:
	gitstats . $@
stats/view: stats
	sensible-browser stats/index.html