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

DEB_PACKAGE_NAME = lazarus
export DEB_BUILD_MAINT_OPTIONS := hardening=+bindnow
export DH_ALWAYS_EXCLUDE := COPYING:LICENSE
export LANG:=C

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/pkg-info.mk

# Documentation type to use chm/html
ifeq (${DEBDOCTYPE},)
DOCTYPE=html
# HTML Converter chmdocs or htmldocs for documentation format (defaults to both)
CONVERTER=${DOCTYPE}docs chmdocs
else
DOCTYPE=${DEBDOCTYPE}
CONVERTER=${DOCTYPE}docs
endif
# Define FPC
ifndef FPC
FPC=/usr/bin/fpc
endif
# Set FPCVER
FPCVER=$(shell ${FPC} -iV)

OS_TARGET=$(subst kfreebsd,freebsd,$(shell dpkg-architecture -qDEB_HOST_ARCH_OS))

FPCTARGET=$(CPU_TARGET)-$(OS_TARGET)
# Get version information from changelog file via pkg-info.mk
DEB_UPSTREAM_MAIN_VERSION:=$(shell echo ${DEB_VERSION_UPSTREAM} | sed -e 's/^\([0-9\.]*\).*/\1/')
DEB_BUILD=$(lastword $(subst -, ,${DEB_VERSION}))
ifndef PACKAGESUFFIX
export PACKAGESUFFIX=-$(shell echo ${DEB_UPSTREAM_MAIN_VERSION} | sed -e 's/^\([0-9]*\.[0-9]*\).*/\1/')
endif
# Get directories
INSTALL_DIR_ARCH=${CURDIR}/debian/tmp
INSTALL_DIR_INDEP=${CURDIR}/debian/tmp2
BIN_DIR=${INSTALL_DIR_ARCH}/usr/bin
LIB_DIR=${INSTALL_DIR_ARCH}/usr/lib/${DEB_PACKAGE_NAME}/${DEB_UPSTREAM_MAIN_VERSION}
DOC_DIR=${INSTALL_DIR_INDEP}/usr/share/doc/${DEB_PACKAGE_NAME}/${DEB_UPSTREAM_MAIN_VERSION}
DOC_DIR_ARCH=${INSTALL_DIR_ARCH}/usr/share/doc/${DEB_PACKAGE_NAME}/${DEB_UPSTREAM_MAIN_VERSION}
SRC_DIR=${INSTALL_DIR_INDEP}/usr/lib/${DEB_PACKAGE_NAME}/${DEB_UPSTREAM_MAIN_VERSION}
# Get utils
ifndef MKDIR
MKDIR=mkdir -p
endif
ifndef CP
CP=cp -Rfpl
endif
ifndef MV
MV=mv
endif
RM:=rm -rf
# Get fpcmake from path if none is specified.
ifndef FPCMAKE
FPCMAKE=fpcmake
endif
# Set default compilation options
DEB_BUILD_FPC_OPT=debian/deb-build-fpc.cfg
DEB_HOST_FPC_OPT=debian/deb-host-fpc.cfg
BUILDOPTS=USESVN2REVISIONINC=0 OPT='@${CURDIR}/${DEB_HOST_FPC_OPT}'
INSTALLOPTS=PREFIX=$(INSTALL_DIR_ARCH)/usr
ifndef LAZBUILD
export LAZBUILD=${CURDIR}/lazbuild --lazarusdir=../..
endif
# Set default compilation options
DEB_HOST_MULTIARCH ?=$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_BUILD_MULTIARCH ?=$(shell dpkg-architecture -qDEB_BUILD_MULTIARCH)

LDFLAGS:=$(strip $(shell DEB_BUILD_MAINT_OPTIONS=$(DEB_BUILD_MAINT_OPTIONS) \
	dpkg-buildflags --get LDFLAGS | \
	sed -e 's/-Wl,//g' -e 's/,/ /g' -e 's1-specs=/usr/share/dpkg/.*\.specs11')) --as-needed
# Build with -pie everywhere except armhf, mips, mipsel
ifeq (,$(filter $(DEB_HOST_ARCH),armhf mips mipsel))
LDFLAGS:=$(LDFLAGS) -pie
endif

#export DH_VERBOSE=1

###################
# Clean
#

clean: clean-patched clean-make-files
	$(RM) debian/tmp2
	dh_clean
	# Make sure the debconf translations are always up-to-date
	debconf-updatepo
	# Make sure the list with timestamps is up-to-date
	# if the check fails, update with "fp-fix-timestamps update" and commit
	[ ! $$(which fp-fix-timestamps) ] || fp-fix-timestamps check

clean-patched: make-files
	@echo "--- Cleaning"
	dh_testdir
# Build qt5 platform everywhere except mips and mipsel
ifeq (,$(filter $(DEB_HOST_ARCH),mips mipsel))
	[ ! -f Makefile ] || $(MAKE) distclean ${BUILDOPTS} LCL_PLATFORM=qt5
endif
	[ ! -f Makefile ] || $(MAKE) distclean ${BUILDOPTS} LCL_PLATFORM=gtk2
	$(MAKE) -C docs/html clean
	find -regex '.*\.\(a\|or?\|so\.*\|ppu\|rsj\)' -delete

###################
# Debian files
#

debian-files: debian-files-stamp
debian-files-stamp:debian/fixdeb debian/*.in
	@echo "--- Creating/fixing *.install files"
	DEB_SUBST_PACKAGESUFFIX=${PACKAGESUFFIX} \
	$< debian/*.in
	# Because we use dh-exec to not build/install the qt flavor on mips/mipsel,
	# we need the *-qt?-*.install files to be executable
	chmod a+x debian/*-qt?-*.install
	touch debian-files-stamp

make-files: make-files-stamp
make-files-stamp:
	# Regenerate make files using fpcmake.
	find * -name Makefile.fpc -exec ${FPCMAKE} -Tall '{}' +
	touch $@

clean-make-files:
	# Remove auto-generated make files.
	find * -name Makefile.fpc -execdir sh -c '${RM} $$(basename {} .fpc)' ';'
	${RM} make-files-stamp

###################
# Arch packages
#

configure: debian-files clean-make-files make-files configure-stamp
configure-stamp:
	dh_testdir
	dh_prep
	# Add version.inc:
	echo \'$(DEB_VERSION)\' > ide/version.inc

	# The next line adds the revision.inc file which is missing in upstream sources
	# Normally this is a number that can be taken from inspecting the tags directory here:
	# http://svn.freepascal.org/cgi-bin/viewvc.cgi/tags/?root=lazarus
	# But let's put something there describes better what the status is.
	echo const RevisionStr = \'Debian package $(DEB_VERSION)\'\; > ide/revision.inc

	# For reproducible builds, we need the above two files to have a fixed timestamp
	# Not added to debian/source/timestamps to keep that auto-updateable for now.
	touch --no-dereference --date="@$${SOURCE_DATE_EPOCH}" ide/version.inc
	touch --no-dereference --date="@$${SOURCE_DATE_EPOCH}" ide/revision.inc

	# Now that we are done with all changes to files in the packaging, let's
	# make sure that all the timestamps are reproducible.
	fp-fix-timestamps touch

	touch configure-stamp

build-arch: debian-files configure build-arch-stamp
build-arch-stamp: ${DEB_HOST_FPC_OPT}
	@echo "--- Building"
	dh_testdir
# Build qt5 platform everywhere except mips and mipsel
ifeq (,$(filter $(DEB_HOST_ARCH),mips mipsel))
	# QT5
	${MAKE} bigide ${BUILDOPTS} LCL_PLATFORM=qt5
	${MV} $(CURDIR)/lazarus $(CURDIR)/lazarus-qt5
endif
	# GTK2
	${MAKE} bigide ${BUILDOPTS} LCL_PLATFORM=gtk2
	${MV} $(CURDIR)/lazarus $(CURDIR)/lazarus-gtk2
	touch build-arch-stamp

install-arch: build-arch install-arch-stamp install-man
install-arch-stamp:
	@echo "--- Installing"
	dh_testdir
	dh_testroot
	dh_installdirs
	# create all necessary directories
	${MKDIR} ${BIN_DIR}
	${MKDIR} ${LIB_DIR}/tools
	${MKDIR} ${LIB_DIR}/components/chmhelp/lhelp
	# Install the IDE & its accessories
# Do not install lazarus-qt5 on mips and mipsel
ifneq (,$(filter $(DEB_HOST_ARCH),mips mipsel))
	${CP} -t ${LIB_DIR} \
		$(CURDIR)/lazarus-gtk2 \
		$(CURDIR)/lazbuild \
		$(CURDIR)/startlazarus \
		$(CURDIR)/languages
else
	${CP} -t ${LIB_DIR} \
		$(CURDIR)/lazarus-gtk2 \
		$(CURDIR)/lazarus-qt5 \
		$(CURDIR)/lazbuild \
		$(CURDIR)/startlazarus \
		$(CURDIR)/languages
endif
	${CP} -t ${LIB_DIR}/tools \
		$(CURDIR)/tools/lazres \
		$(CURDIR)/tools/lrstolfm \
		$(CURDIR)/tools/svn2revisioninc \
		$(CURDIR)/tools/updatepofiles
	${CP} -t ${LIB_DIR}/components/chmhelp/lhelp \
		$(CURDIR)/components/chmhelp/lhelp/lhelp
	# Install the library files
	find -name debian -prune -or '(' -name lib -or -name units ')' -print | xargs ${CP} --parents -t ${LIB_DIR}
	# Remove READM.txt files from output directories
	find ${LIB_DIR} '(' -name '*.or' -or -wholename '*/lib/README.txt' ')' -delete
	# Mark package as manually compilable and install them
	for package in `find -name '*.lpk'` ; \
	do \
		${MKDIR} `dirname "${LIB_DIR}/$${package}"` ; \
		sed -e 's@\(\W*\)<CompilerOptions>.*@\1<AutoUpdate Value="Manually"/>\n&@' "$${package}" > "${LIB_DIR}/$${package}" ; \
	done
	# Install packages global links
	${CP} -t ${LIB_DIR}/packager $(CURDIR)/packager/globallinks
	# copy icons and menu entries for the GNOME menu
	${MKDIR} $(INSTALL_DIR_ARCH)/usr/share/pixmaps
	${MKDIR} $(INSTALL_DIR_ARCH)/usr/share/applications
	# the following source file is not completely correct, it produces a
	# warning in imagemagick
	convert -geometry 32x32 $(CURDIR)/images/ide_icon48x48.png $(INSTALL_DIR_ARCH)/usr/share/pixmaps/lazarus-${DEB_UPSTREAM_MAIN_VERSION}.xpm
	sed -e 's/Lazarus.*/& (${DEB_UPSTREAM_MAIN_VERSION})/' -e 's/Exec=startlazarus/&-${DEB_UPSTREAM_MAIN_VERSION}/' $(CURDIR)/install/lazarus.desktop > $(INSTALL_DIR_ARCH)/usr/share/applications/lazarus-${DEB_UPSTREAM_MAIN_VERSION}.desktop
	# Install configuration files
	${MKDIR} $(INSTALL_DIR_ARCH)/etc/lazarus${PACKAGESUFFIX}
	sed -e "s#__LAZARUSDIR__#/usr/lib/lazarus/${DEB_UPSTREAM_MAIN_VERSION}/#" -e 's#__FPCSRCDIR__#/usr/share/fpcsrc/$$(FPCVER)/#' ${CURDIR}/tools/install/linux/environmentoptions.xml > $(INSTALL_DIR_ARCH)/etc/lazarus${PACKAGESUFFIX}/environmentoptions.xml
	fpcsubst -d LazarusVersion=${DEB_UPSTREAM_MAIN_VERSION} -i ${CURDIR}/tools/install/linux/helpoptions.xml -o $(INSTALL_DIR_ARCH)/etc/lazarus${PACKAGESUFFIX}/helpoptions.xml
	# Install contributer list
	${MKDIR} ${DOC_DIR_ARCH}/docs
	${CP} -t ${DOC_DIR_ARCH}/docs \
		$(CURDIR)/docs/lazdoc.css \
		$(CURDIR)/docs/Contributors.txt \
		$(CURDIR)/docs/acknowledgements.txt
	find ${INSTALL_DIR_ARCH} -empty -delete

	# The following lines are taken from https://wiki.debian.org/dedup.debian.net
	# Replace duplicate files in lcl-* with symlinks
	# directories are listed to make sure the "originals" end up in nogui which the
	# gtk2 package depend on
# Do not install qt5 components on mips and mipsel
ifneq (,$(filter $(DEB_HOST_ARCH),mips mipsel))
	rdfind -outputname /dev/null -makesymlinks true \
		${LIB_DIR}/units/*/nogui \
		${LIB_DIR}/units/*/gtk2 \
		${LIB_DIR}/components/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/gtk2 \
		${LIB_DIR}/components/*/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/*/gtk2 \
		${LIB_DIR}/components/*/*/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/*/*/gtk2
else
	rdfind -outputname /dev/null -makesymlinks true \
		${LIB_DIR}/units/*/nogui \
		${LIB_DIR}/units/*/gtk2 \
		${LIB_DIR}/units/*/qt5 \
		${LIB_DIR}/components/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/gtk2 \
		${LIB_DIR}/components/*/*/*/qt5 \
		${LIB_DIR}/components/*/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/*/gtk2 \
		${LIB_DIR}/components/*/*/*/*/qt5 \
		${LIB_DIR}/components/*/*/*/*/*/nogui \
		${LIB_DIR}/components/*/*/*/*/*/gtk2 \
		${LIB_DIR}/components/*/*/*/*/*/qt5
endif

	# Fix those symlinks to make them relative
	symlinks -r -s -c ${LIB_DIR}

	touch install-arch-stamp

build-indep:
install-indep:

install-man: install-man-stamp
install-man-stamp:
	# Install man pages
	$(MAKE) -C install/man install $(INSTALLOPTS)
	for s in ${INSTALL_DIR_ARCH}/usr/share/man/man[1-9] ; do cd $${s} && for f in *.[1-9].gz ; do ${MV} $${f} $${f%%.*}-${DEB_UPSTREAM_MAIN_VERSION}."$${f#*.}" ; done ; done || true
	touch install-man-stamp

###################
# Documentation
#

build-doc: build-doc-stamp
build-doc-stamp:
	@echo "--- Building Documentation"
	dh_testdir
	# Until the whole locale is properly set to include at least UTF-8 in some
	# more generic way than on a per d/rules file basis, we need to set the
	# locale here to get reproducible builds (because of sorting in index
	# pages) and to fix some characters in some documentation files that are
	# non-ascii.
	LC_ALL=C.UTF-8 $(MAKE) -C docs/html ${CONVERTER}
	touch build-doc-stamp

install-doc: build-doc install-doc-stamp
install-doc-stamp: ${DEB_BUILD_FPC_OPT}
	@echo "--- Installing Documentation"
	dh_testdir
	dh_testroot
	${MAKE} -C docs/html ${DOCTYPE}install INSTALL_PREFIX=${INSTALL_DIR_INDEP}/usr INSTALL_DOCDIR=${DOC_DIR}
	cd docs ; ${CP} --parents -t ${DOC_DIR} \
	  index.html \
	  images/laztitle.png
	find ${DOC_DIR} -empty -delete

	# The following lines are taken from https://wiki.debian.org/dedup.debian.net
	# Replace duplicate files with symlinks
	rdfind -outputname /dev/null -makesymlinks true ${DOC_DIR}
	# Fix those symlinks to make them relative
	symlinks -r -s -c ${DOC_DIR}

	touch install-doc-stamp

###################
# Source
#

install-source: clean-patched install-source-stamp
install-source-stamp:
	@echo "--- Cleaning the tree and copying the source code"
	dh_testdir
	dh_testroot
	${MKDIR} ${SRC_DIR}
	${CP} -t ${SRC_DIR} \
		$(CURDIR)/Makefile* \
		$(CURDIR)/components \
		$(CURDIR)/converter \
		$(CURDIR)/debugger \
		$(CURDIR)/designer \
		$(CURDIR)/doceditor \
		$(CURDIR)/examples \
		$(CURDIR)/ide \
		$(CURDIR)/images \
		$(CURDIR)/lcl \
		$(CURDIR)/packager \
		$(CURDIR)/test \
		$(CURDIR)/tools
	# Remove files already installed in binary packages
	find ${SRC_DIR} -name '*.lpk' -delete
	${RM} ${SRC_DIR}/packager/globallinks
	find ${SRC_DIR} -regex '.*\.\(bmp\|jpg\|png\|xpm\)' -delete
	$(RM) ${SRC_DIR}/components/lazreport/license*.txt
	find ${SRC_DIR} -empty -delete

	# Fix some permissions
	find ${SRC_DIR}/components ${SRC_DIR}/ide -type f -perm /u+x,g+x,o+x \
		! \( -name "*.sh" -o -name "*.pl" \) -exec chmod a-x {} \;

	touch install-source-stamp

###################
# Generic
#

build: build-arch build-indep
install: install-arch install-indep
binary: binary-arch binary-indep


###################
# Deb building
#

configure-indep: configure

binary-indep: configure-indep install-doc install-source
	@echo "--- Building: arch-indep packages"
	dh_testdir
	dh_testroot
	dh_installdocs -i -X.in
	dh_installchangelogs -i
	dh_install -i --sourcedir=debian/tmp2
	dh_missing --fail-missing
	dh_lintian -i
	dh_compress -i -X.pdf -X.chm -X.xct
	dh_fixperms
	dh_installdebconf -i
	dh_installdeb -i
	dh_gencontrol -i
	dh_md5sums -i
	dh_builddeb -i $(DEB_DH_BUILDDEB_ARGS)

binary-arch: install-arch
	@echo "--- Building: arch packages"
	dh_testdir
	dh_testroot
	dh_link
	dh_install -a
	dh_installdocs -a -X.in
	dh_installchangelogs -a
	dh_installexamples -a
	dh_installmenu
	fpc-depends
	dh_installman -a
	dh_missing --fail-missing
	dh_strip -a
	dh_compress -a
	dh_fixperms
	dh_lintian -a
	dh_installdebconf -a
	dh_installdeb -a
	dh_shlibdeps -a
	dh_gencontrol -a -- \
		-VBuild-Using="$$(dpkg-query --show --showformat='$${version}' fpc)"
	dh_md5sums -a
	dh_builddeb -a $(DEB_DH_BUILDDEB_ARGS)

.PHONY: build clean binary binary-arch \
	binary-indep debian-files build-arch \
	install install-indep install-arch \
	configure configure-indep make-files clean-make-files \
	get-orig-source build-doc

debian/%:debian/fixdeb debian/changelog debian/%.in
	DEB_SUBST_PACKAGESUFFIX=${PACKAGESUFFIX} \
	DEB_SUBST_TARGET=${FPCTARGET} \
	$< --gen-control $@.in

${DEB_BUILD_FPC_OPT}:
	echo '# FPC configuration file for build system tools' > $@
	if [ -n "${LDFLAGS}" ]; then echo '-k${LDFLAGS}' >> $@; fi
	echo '-Fl/usr/lib/${DEB_BUILD_MULTIARCH}' >> $@

${DEB_HOST_FPC_OPT}:
	echo '# FPC configuration file for host system applications' > $@
	if [ -n "${LDFLAGS}" ]; then echo '-k${LDFLAGS}' >> $@; fi
	echo '-Fl/usr/lib/${DEB_HOST_MULTIARCH}' >> $@