#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

# detect if build targets experimental suite (or is a draft)
DEB_SUITE_EXP = $(filter experimental% UNRELEASED,$(DEB_DISTRIBUTION))

# generate documentation unless nodoc requested
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
DOCS = README.html README.txt
endif

ESLINT = eslint --format tap
MOCHA = mocha --reporter tap

# tolerate failures on stdin listed as argument
TAP_TODO = perl -MTAP::Parser -E '\
 %skip = map {@parts = split /\b::\b/; $$parts[0] => $$parts[1]} @ARGV;\
 open my $$fh, "<&STDIN";\
 $$parser = TAP::Parser->new( { source => $$fh } );\
 while ( my $$res = $$parser->next ) {\
	if ($$res->is_test) {\
		$$yaml = undef;\
		unless ($$res->is_ok) {\
			while (grep {$$res->as_string =~ /$$_/} keys %skip) {\
				if ($$skip{$$_}) {\
					$$yaml = $$skip{$$_};\
				} else {\
					$$todo++; print "\# TODO: "}\
				last}}};\
	if ($$res->is_yaml and $$yaml and $$res->as_string =~ /$$yaml/s) {\
		$$todo++; print "\# TODO: "};\
	say $$res->as_string}; \
 say "\# skipped $$todo/",0+@ARGV; \
 exit ($$parser->tests_run - $$parser->passed - $$todo)'

ESLINT_BROKEN = \
 lib/utils/rjs.js \
 lib/utils/ast.js \
 lib/rules/amd-function-arity.js \
 lib/rules/sort-amd-paths.js

MOCHA_BROKEN = \
 tests/lib/rules/enforce-define.js

override_dh_auto_build: $(DOCS)

override_dh_auto_test:
	$(strip find lib tests/lib -type f -name '*.js' \
		$(patsubst %,-not -path '%',$(ESLINT_BROKEN)) \
		-exec $(ESLINT) {} +)
	$(ESLINT) $(ESLINT_BROKEN) | $(TAP_TODO) \
		'lib/utils/rjs.js::Arrow function used ambiguously with a conditional expression.*line: 82.*ruleId: no-confusing-arrow' \
		"lib/utils/ast.js::Assignment to function parameter 'node'.*line: 151.*ruleId: no-param-reassign" \
		'lib/rules/amd-function-arity.js::Arrow function used ambiguously with a conditional expression.*line: 82.*ruleId: no-confusing-arrow' \
		'lib/rules/sort-amd-paths.js::Arrow function used ambiguously with a conditional expression.*line: 74.*ruleId: no-confusing-arrow'
	$(strip find tests/lib/*/*.js \
		$(patsubst %,-not -path '%',$(MOCHA_BROKEN)) \
		-exec $(MOCHA) '{}' +)
	$(MOCHA) $(MOCHA_BROKEN) | $(TAP_TODO) \
		'not ok 32 enforce-define invalid' \
		'not ok 33 enforce-define invalid' \
		'not ok 34 enforce-define invalid' \
		'not ok 35 enforce-define invalid'

override_dh_installdocs:
	dh_installdocs --all -- $(DOCS)

override_dh_clean:
	dh_clean -- $(DOCS)

%.html: %.md
	pandoc --from gfm-raw_html --to html --standalone --output $@ $<

%.txt: %.md
	pandoc --from gfm-raw_html --to plain --output $@ $<

%:
	dh $@
