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

DESTDIR := $(CURDIR)/debian/tmp

include /usr/share/ocaml/ocamlvars.mk

export OCAMLFIND_DESTDIR := $(DESTDIR)/$(OCAML_STDLIB_DIR)
export OCAMLFIND_DLLDIR := $(DESTDIR)/$(OCAML_DLL_DIR)

ifeq ($(OCAML_HAVE_OCAMLOPT),yes)
  BUILD_TARGET := byte-code-library native-code-library
  INSTALL_TARGET := libinstall
else
  BUILD_TARGET := byte-code-library
  INSTALL_TARGET := libinstall-byte-code
endif

%:
	dh $@ --with ocaml

.PHONY: override_dh_auto_build
override_dh_auto_build:
	$(MAKE) $(BUILD_TARGET)

.PHONY: override_dh_auto_install
override_dh_auto_install:
	mkdir -p $(OCAMLFIND_DESTDIR) $(OCAMLFIND_DLLDIR)
	$(MAKE) $(INSTALL_TARGET)
	rm $(OCAMLFIND_DLLDIR)/*.owner

.PHONY: override_dh_install
override_dh_install:
	dh_install --fail-missing

# Make a release
release: SOURCE=$(shell dpkg-parsechangelog | awk '/^Source:/ { print $$2 }')
release: VERSION=$(shell dpkg-parsechangelog | awk '/^Version:/ { print $$2 }')
release: UPSTREAM_VERSION=$(shell VERSION="$(VERSION)"; echo $${VERSION%-*})
release: DIR=$(shell basename "$$(pwd)")
release: ORIG_NAME=../$(SOURCE)_$(UPSTREAM_VERSION).orig.tar.gz
release:
	@if [ "$(VERSION)" = $(UPSTREAM_VERSION) ]; then		\
	  echo "Error: Missing debian revision in $(VERSION).";		\
	  exit 1;							\
	fi
	@if [ -n "$(shell git status --porcelain)" ]; then		\
	  echo "Error: Uncommited changed.";				\
	  exit 1;							\
	fi
	@if ! git branch | grep -q "^* master$$"; then			\
	  echo "Error: Not in master branch.";				\
	  exit 1;							\
	fi
	@if git tag | grep -q "^debian/$(VERSION)$$"; then		\
	  echo "Error: Release $(VERSION) already exists.";		\
	  exit 1;							\
	fi
	@if git tag | grep -q "^upsteam/$(UPSTREAM_VERSION)$$"; then	\
	  echo "Upstream $(UPSTREAM_VERSION) already exists.";		\
	else								\
	  echo "Creating $(ORIG_NAME) ...";				\
	  git archive --format=tar.gz --output=$(ORIG_NAME)		\
		      --prefix=$(SOURCE)-$(UPSTREAM_VERSION)/		\
		      --worktree-attributes HEAD;			\
	  git-import-orig --no-merge --pristine-tar 			\
			  --upstream-version=$(UPSTREAM_VERSION)	\
			  $(ORIG_NAME);					\
	fi
	@echo "Tagging release debian/$(VERSION)"
	@git tag "debian/$(VERSION)"
