#!/usr/bin/make -f
# debian/rules for ocamlduce

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

include /usr/share/ocaml/ocamlvars.mk

# We do as in ocaml: the ABI is the upstream version number and we
# need to use a special ocamlobjinfo for OCamlDuce compiled interfaces
export OCAMLOBJINFO := debian/tmp/usr/bin/ocamlduceobjinfo
OCAMLDUCE_ABI := $(shell head -n1 debian/changelog|awk -F'[()-]' '{print $$2}'|sed 's/~/+/g')

BUILD_TARGET := $(if $(OCAML_OPT_ARCH),world.opt,world)
INSTALL_TARGET := installbyte $(if $(OCAML_OPT_ARCH),installopt)

OCAML_SRCDIR := ocaml-$(OCAML_ABI)
MAKE_DUCE := $(MAKE) -C $(OCAML_SRCDIR) -f Makefile.ocamlduce
ODOC_DESTDIR := debian/tmp$(OCAML_STDLIB_DIR)/ocamlduce/ocamldoc

%:
	dh $@ --with ocaml

.PHONY: override_dh_auto_configure
override_dh_auto_configure:
	$(MAKE) prepare
	cd $(OCAML_SRCDIR) && for u in `cat debian-patches/series`; do \
	  patch -p1 < debian-patches/$$u; \
	done
	for ext in sub guess; do \
	  if [ -f /usr/share/misc/config.$$ext ]; then \
	    cp -f /usr/share/misc/config.$$ext $(OCAML_SRCDIR)/config/gnu/config.$$ext; \
	  fi; \
	done
	cd $(OCAML_SRCDIR) && \
	  ./configure -prefix /usr -libdir $(OCAML_STDLIB_DIR)
	sed -i \
	  -e "s%LIBDIR=.*$$%LIBDIR=\$$(PREFIX)$(patsubst /usr/%,/%,$(OCAML_STDLIB_DIR))%g" \
	  $(OCAML_SRCDIR)/config/Makefile

.PHONY: override_dh_auto_build
override_dh_auto_build:
	$(MAKE_DUCE) $(BUILD_TARGET)
	cd $(OCAML_SRCDIR) && ocamlbuild -lflags -I,otherlibs/ocamlduce tools/objinfo.byte

.PHONY: override_dh_auto_install
override_dh_auto_install:
	$(MAKE_DUCE) PREFIX=../debian/tmp/usr $(INSTALL_TARGET)
	install -m 755 $(OCAML_SRCDIR)/_build/tools/objinfo.byte \
	  debian/tmp/usr/bin/ocamlduceobjinfo
	mkdir -p $(ODOC_DESTDIR)
	find $(OCAML_STDLIB_DIR)/ocamldoc -type f -printf \
	  '$(OCAML_SRCDIR)/_build/ocamldoc/%P\0' \
	  | xargs -0 cp -t $(ODOC_DESTDIR)

.PHONY: override_dh_auto_clean
override_dh_auto_clean:
	rm -Rf $(OCAML_SRCDIR)

.PHONY: override_dh_ocaml
override_dh_ocaml:
	dh_ocaml --checksum=$(OCAMLDUCE_ABI) \
	  --runtime-map=ocamlduce:ocamlduce-base \
	  -Xtoplevellib.cma -Xocamldoc \
	  --nodefined-map=ocamlduce:Topdirs,Toploop,Topmain,Topstart
