#!/usr/bin/make -f

include /usr/share/dpkg/default.mk

platform_tr = $(shell { grep '^$(1)\b' debian/platforms.table || echo '	unsupported:$(1)'; } | cut -f2)

NIMFLAGS = $(addprefix --passC:,$(CPPFLAGS)) $(addprefix --passC:,$(CFLAGS)) $(addprefix --passL:,$(LDFLAGS))
ifeq ($(DEB_HOST_ARCH_OS),kfreebsd)
	# work around https://github.com/nim-lang/Nim/issues/3165
	NIMFLAGS += --parallelBuild:1
endif

# TODO: remove this when https://github.com/nim-lang/Nim/issues/3506 is fixed
EXTRA_KOCHFLAGS = -p:. -p:lib/packages/docutils

%:
	dh $@

override_dh_auto_build:
	$(MAKE) -f makefile myos=$(call platform_tr,$(DEB_HOST_ARCH_OS)) mycpu=$(call platform_tr,$(DEB_HOST_ARCH_CPU))
	./bin/nim c $(NIMFLAGS) koch
	# Build until convergence; we must do this here, not dh_auto_test, to pick up
	# any changes in debian/patches. see also https://github.com/nim-lang/csources/issues/12
	PATH=./bin/:$$PATH ./koch boot -d:release $(EXTRA_KOCHFLAGS) $(NIMFLAGS)
	PATH=./bin/:$$PATH ./koch web
	help2man --name="Nim Language Compiler" -s1 -N --version-string="$(DEB_VERSION)" \
		-i debian/nim.h2m -o debian/nim.1 ./bin/nim

override_dh_auto_install:
	PATH=./bin/:$$PATH ./koch install debian/tmp
	cp -a web/upload debian/html
	find debian/html -name '*.idx' \
		-delete
	ln -sf overview.html debian/html/index.html

override_dh_auto_test:
	if [ -f compiler/nim2 ]; then cmp ./bin/nim compiler/nim2; else cmp ./bin/nim compiler/nim1; fi
	# TODO: do this with autopkgtest instead; it requires libsqlite3-0 and nodejs
	#PATH=./bin:$$PATH ./koch test

override_dh_auto_clean:
	rm -f ./koch tools/nimweb tools/niminst/niminst compiler/nim compiler/nim0 compiler/nim1 compiler/nim2
	rm -rf bin/ web/upload/
	# TODO: use this instead when https://github.com/nim-lang/Nim/issues/2127 is fixed
	#PATH=./bin:$$PATH ./koch clean
	find . -name nimcache \
		-prune -execdir rm -rf nimcache \;
	find . -name '*.o' \
		-delete
	find doc \( -name '*.idx' -o -name '*.html' \) \
		-delete
	find examples lib tests -type f -executable -and -not -name '*.nim' \
		-delete
	rm -f testament.db testresults.*

override_dh_installdocs:
	dh_installdocs -Xcopying.txt

override_dh_clean:
	dh_clean
	rm -f debian/nim.1
	rm -rf debian/html
