#!/usr/bin/make -f

include /usr/share/javahelper/java-vars.mk
include /usr/share/dpkg/pkg-info.mk

export LEIN_HOME=$(CURDIR)/.lein
export LEIN_OFFLINE=true

SUB_PROJECTS=org.ring-clojure/ring-core-protocols org.ring-clojure/ring-websocket-protocols ring/ring-core ring/ring-servlet org.ring-clojure/ring-jakarta-servlet ring/ring-jetty-adapter

ns = $(firstword $(subst /, ,$1))
project = $(word 2,$(subst /, ,$1))

%:
	dh $@ --with maven_repo_helper --without=single-binary

override_dh_auto_configure:
	cp -rs /usr/share/maven-repo debian

override_dh_auto_build:
	$(foreach sub,$(SUB_PROJECTS), \
		set -e; \
		echo "---> Building $(sub)"; \
		export NS="$(subst .,/,$(call ns,$(sub)))"; \
		export PROJECT="$(call project,$(sub))"; \
		cd $(CURDIR)/$${PROJECT}; \
		lein pom ../debian/$${PROJECT}.pom.xml; \
		lein jar; \
		cd target && ln -sf $${PROJECT}-$(DEB_VERSION_UPSTREAM).jar $${PROJECT}.jar; \
		cd $(CURDIR); \
		mkdir -p debian/maven-repo/$${NS}/$${PROJECT}/debian; \
		cp -s $(CURDIR)/$${PROJECT}/target/$${PROJECT}.jar \
			debian/maven-repo/$${NS}/$${PROJECT}/debian/$${PROJECT}-debian.jar; \
		cp -s $(CURDIR)/debian/$${PROJECT}.pom.xml \
			debian/maven-repo/$${NS}/$${PROJECT}/debian/$${PROJECT}-debian.pom; \
	)

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	$(foreach sub,$(SUB_PROJECTS), \
		set -e; \
		export PROJECT="$(call project,$(sub))"; \
		cd $(CURDIR)/$${PROJECT}; \
		if [ -d test ]; then \
			echo "---> Testing $(sub)"; \
			if ! lein test; then \
				cat /tmp/clojure-*.edn; \
				exit 1; \
			fi; \
		fi; \
	)
endif

execute_after_mh_install:
	# signal the deps resolver not to modify our poms
	touch .debianVersion
	# resolve dependencies for our binary packages using maven
	# see d/maven.ignoreRules about deps built from the same source package
	export CLASSPATH="/usr/share/java/maven-repo-helper.jar:/usr/share/java/maven-packager-utils.jar"; \
	for f in debian/*.poms; do \
		export p=$$(echo $$f | sed 's,debian/\(.*\)\.poms,\1,'); \
		mh_patchpoms -p$$p --debian-build --no-rules --set-version=debian; \
		mh_resolve_dependencies --non-interactive --non-explore --offline --build -p$$p; \
		perl -p -i -e 's/maven\./maven:/' debian/$${p}.substvars; \
	done
	jh_classpath

override_dh_clean:
	rm -f .lein-failures
	rm -Rf .lein debian/maven-repo
	for sub in $(SUB_PROJECTS) ; do \
		rm -f .lein-failures; \
		rm -f debian/$$sub.pom.xml; \
		rm -Rf $$sub/target; \
	done
	dh_clean
