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

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

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

PACKAGE := ocaml-dune
ALL_PACKAGES := $(shell dh_listpackages)
DISTDIR = $(PACKAGE)-$(DEB_VERSION_UPSTREAM)
UPSTREAM_TARBALL = $(wildcard ../$(PACKAGE)_$(DEB_VERSION_UPSTREAM).orig.tar.*)
SRCTARBALL = $(PACKAGE)-source-$(DEB_VERSION_UPSTREAM).tar
BUILD_DATE := $(shell date -d@$(DEB_TIMESTAMP) -R)

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)

execute_after_dh_auto_install-indep:
	mkdir -p debian/ocaml-dune-source/usr/src
	cp $(TARBALL_TARGET) debian/ocaml-dune-source/usr/src
endif
