#!/usr/bin/make -f

# resolve DEB_VERSION_UPSTREAM
include /usr/share/dpkg/pkg-info.mk

# TODO: simplify rules when haskell-devscripts supports DEB_SRCDIR
#DEB_SRCDIR = pandoc-cli

DEB_CABAL_FILE = pandoc-cli/pandoc-cli.cabal
DEB_ENABLE_TESTS = yes
DEB_CABAL_PACKAGE = pandoc-cli

include /usr/share/cdbs/1/rules/debhelper.mk

# use forked Haskell build helper script to support DEB_CABAL_FILE
-include debian/hlibrary.mk

pkg = $(DEB_SOURCE_PACKAGE)

ABI = $(shell dpkg-query --showformat='$${source:Version}' --show libghc-pandoc-types-dev)
LIB = $(firstword $(subst +, ,$(DEB_VERSION_UPSTREAM)))

# Fix exception thrown building documentation:
# haddock: internal error: <stdout>: commitBuffer: invalid argument (invalid character)
export LANG=C.UTF-8

# Use threaded RTS only when supported
DEB_SETUP_GHC_CONFIGURE_ARGS += $(if $(wildcard /usr/lib/ghc-$(GHC_VERSION)/libHSrts_thr.a),,--flags=-threaded)

# Disable timer to help build on slow arches like hppa
DEB_SETUP_GHC_CONFIGURE_ARGS += --ghc-options="+RTS -V0 -RTS"

# Reduce compile-time memory utilization on low-memory architectures
ifneq (,$(filter $(DEB_BUILD_ARCH),armel armhf hppa mips mipsel))
DEB_SETUP_GHC_CONFIGURE_ARGS += --ghc-options="-optc--param -optcggc-min-expand=10 -O0"
endif

# avoid "relocation R_LARCH_B26 overflow" during static linking
# (see bug#1071205)
ifneq (,$(filter $(DEB_BUILD_ARCH),loong64))
DEB_SETUP_GHC_CONFIGURE_ARGS += --ghc-options="-optc-mcmodel=medium"
endif

ifneq (,$(filter $(DEB_HOST_ARCH_CPU), i386))
DEB_SETUP_GHC_CONFIGURE_ARGS += --ghc-options="-O0"
endif

DEB_SETUP_GHC_CONFIGURE_ARGS += $(if $(filter nocheck,$(DEB_BUILD_OPTIONS)),,-ftests)

DEB_INSTALL_DOCS_ALL += README.md

build/$(pkg):: build-ghc-stamp

post-install/$(pkg)::
	debian/tmp-inst-*/usr/bin/pandoc --bash-completion \
		> debian/pandoc.bash-completion
binary-install/$(pkg)::
	dh_bash-completion
clean::
	rm -f debian/pandoc.bash-completion

# populate project at root where haskell-devscripts can use it
SRC_DATA = $(filter-out COPYING.md,\
 $(notdir $(wildcard pandoc-cli/*)))
pre-build::
	rm -rf $(SRC_DATA)
	cp --archive --target-directory=. $(addprefix pandoc-cli/,$(SRC_DATA))
clean::
	rm -rf $(SRC_DATA)

DEB_DH_GENCONTROL_ARGS_$(pkg) = -- \
 -V"pandoc:Abi=$(ABI)" \
 -V"pandoc:Lib=$(LIB)"

# generate man page
DEB_INSTALL_MANPAGES_$(pkg) = man/pandoc.1
build/$(pkg):: man/pandoc.1
man/pandoc.1: MANUAL.txt
	dist-ghc/build/pandoc/pandoc $< -f markdown -t man -s \
		--lua-filter man/manfilter.lua \
		--include-before-body man/pandoc.1.before \
		--include-after-body man/pandoc.1.after \
		--metadata author="" \
		--variable footer="pandoc $(LIB)" \
		-o $@
clean::
	rm -f man/pandoc.1
