#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
#export DH_OPTIONS=-v

include /usr/share/ocaml/ocamlvars.mk

PACKAGE := ocaml-dune
ALL_PACKAGES := $(shell dh_listpackages)
UPSTREAM_VERSION = $(shell dpkg-parsechangelog -S Version | { read u; echo $${u%-*}; })
DISTDIR = $(PACKAGE)-$(UPSTREAM_VERSION)
UPSTREAM_TARBALL = $(wildcard ../$(PACKAGE)_$(UPSTREAM_VERSION).orig.tar.*)
SRCTARBALL = $(PACKAGE)-source-$(UPSTREAM_VERSION).tar
BUILD_DATE := $(shell dpkg-parsechangelog --show-field=Date)

ifneq (,$(findstring ocaml-dune-source,$(ALL_PACKAGES)))
  TARBALL_TARGET = debian/$(SRCTARBALL)
endif

DESTDIR=$(CURDIR)/debian/tmp

DEB_DUNE_OTHER_PACKAGES := dune-build-info ordering xdg fs-io top-closure

%:
	dh $@ --with ocaml

override_dh_auto_configure: $(TARBALL_TARGET)
	./configure --libdir $(OCAML_STDLIB_DIR)

override_dh_auto_build:
	ocaml boot/bootstrap.ml
	./dune.exe build --release --profile dune-bootstrap dune.install
	./dune.exe build --release $(addsuffix .install,$(DEB_DUNE_OTHER_PACKAGES))

override_dh_auto_install:
	./dune.exe install --release --destdir=$(DESTDIR) --prefix=/usr --libdir=$(OCAML_STDLIB_DIR) dune $(DEB_DUNE_OTHER_PACKAGES)
	rm -rf $(addprefix debian/tmp/usr/doc/,$(DEB_DUNE_OTHER_PACKAGES))
	rm -f debian/tmp/usr/doc/dune/LICENSE.md

override_dh_auto_test:
# Upstream tests have many dependencies; rely on autopkgtest instead

ifneq (,$(TARBALL_TARGET))
$(TARBALL_TARGET): $(UPSTREAM_TARBALL)
	mkdir -p debian/$(DISTDIR)
# Copy upstream tarball
	cp $< debian/$(DISTDIR)
# Copy debian/patches and set permissions (workaround for #796257)
	if [ -d debian/patches ]; then \
	  cp -a debian/patches debian/$(DISTDIR)/debian-patches; \
	  chmod 755 debian/$(DISTDIR)/debian-patches; \
	  chmod 644 debian/$(DISTDIR)/debian-patches/*; \
	fi
# Create the tarball and cleanup
	cd debian && find $(DISTDIR) -not -type d -print0 | \
		LC_ALL=C sort --zero-terminated | \
		tar --create --null --files-from=- \
			--file=$(abspath $@) --mtime="$(BUILD_DATE)" \
			--owner=root --group=root --numeric-owner
	rm -Rf debian/$(DISTDIR)
endif
