#!/usr/bin/make -f
ifeq (,$(shell dh_testdir || echo no))
DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_BUILD_ARCH  ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH)

GRE_VERSION := 1.9.1

# The VERSION_FILTER transforms upstream version patterns to versions
# useable in debian/changelog. Versions are to be transformed as follows:
# 4.0      -> 4.0
# 4.0pre   -> 4.0~pre
# 4.0b5    -> 4.0~b5
# 4.0b5pre -> 4.0~b5~pre
# That should ensure the proper ordering
VERSION_FILTER := sed 's/\([0-9]\)\([a-z]\)/\1~\2/g'
UPSTREAM_VERSION := $(shell cat browser/config/version.txt)
GRE_MILESTONE := $(shell config/milestone.pl --topsrcdir .| $(VERSION_FILTER))
SO_VERSION := $(shell awk -F'[\t =]+' '$$1 == "SO_VERSION" {print $$2}' js/src/Makefile.in)
# Last version in debian/changelog
DEBIAN_VERSION := $(shell dpkg-parsechangelog | sed -n 's/^Version: *// p')
# Debian part of the above version (anything after the last dash)
DEBIAN_RELEASE := $(lastword $(subst -, ,$(DEBIAN_VERSION)))
# Upstream part of the debian/changelog version (anything before the last dash)
UPSTREAM_RELEASE := $(DEBIAN_VERSION:%-$(DEBIAN_RELEASE)=%)

# Check if the GRE_VERSION defined above matches the actual milestone
ifeq (,$(filter $(GRE_VERSION).%,$(GRE_MILESTONE)))
$(error GRE_VERSION ($(GRE_VERSION)) doesn't match GRE_MILESTONE ($(GRE_MILESTONE)))
endif

# Check if the version in debian/changelog matches actual upstream version
# as VERSION_FILTER transforms it.
FILTERED_UPSTREAM_VERSION := $(shell echo $(UPSTREAM_VERSION) | $(VERSION_FILTER))
ifneq ($(FILTERED_UPSTREAM_VERSION),$(UPSTREAM_RELEASE))
$(error Upstream version in debian/changelog ($(UPSTREAM_RELEASE)) doesn't match actual upstream version ($(FILTERED_UPSTREAM_VERSION)))
endif

LIB_DIR := /usr/lib/iceweasel
SHARE_DIR := /usr/share/iceweasel

CFLAGS := -g
MAIN_LDFLAGS := -Wl,--as-needed

AUTOCONF_DIRS := build/autoconf js/src/build/autoconf

ifneq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
	CONFIGURE_FLAGS += --disable-optimize
endif

ifeq ($(DEB_BUILD_ARCH),alpha)
	MAIN_LDFLAGS += -Wl,--no-relax
endif

ifeq ($(DEB_BUILD_ARCH),ppc64)
	CFLAGS += -mminimal-toc
endif

ifneq (,$(filter debug,$(DEB_BUILD_OPTIONS)))
	CONFIGURE_FLAGS += --enable-debug
endif
ifeq (,$(filter debug noopt,$(DEB_BUILD_OPTIONS)))
	GENSYMBOLS_FLAGS := -c4
endif

ifeq (default,$(origin CC))
CC := gcc
endif
ifeq (default,$(origin CXX))
CXX := g++
endif
CXXFLAGS := $(CFLAGS)
ifeq (,$(shell dpkg --compare-versions $(shell $(CXX) -dumpversion) '>=' 4.4 || echo no))
CXXFLAGS += -std=gnu++0x
endif

export CC CXX CFLAGS CXXFLAGS

JS_LDFLAGS := $(MAIN_LDFLAGS)
JS_LDFLAGS += -Wl,--version-script=$(CURDIR)/debian/symbols.filter

GENERATED_FILES += debian/dh/dh_xulrunner.1

debian/dh/dh_xulrunner.1: debian/dh/dh_xulrunner
	pod2man -c Debhelper -r $(GRE_VERSION) $^ > $@

build-xulrunner/dist/bin/npapi_getinfo: debian/dh/npapi_getinfo.c
	$(CC) -o $@ $< -Imodules/plugin/base/public -ldl -Wl,-rpath,\$$ORIGIN

IN_FILES := $(wildcard debian/*.in debian/dh/*.in)
define preprocess
$(subst SO_VERSION,$(SO_VERSION),$(subst GRE_VERSION,$(GRE_VERSION),$(1:.in=))): $(1)
PREPROCESSED_FILES += $(subst SO_VERSION,$(SO_VERSION),$(subst GRE_VERSION,$(GRE_VERSION),$(1:.in=)))
endef
$(foreach f,$(IN_FILES),$(eval $(call preprocess, $(f))))

GENERATED_FILES += $(filter-out debian/control,$(PREPROCESSED_FILES))

ifeq ($(shell lsb_release -sc),lenny)
DICT_DIR := /usr/share/myspell/dicts
else
DICT_DIR := /usr/share/hunspell
endif

$(PREPROCESSED_FILES):
	sed $(foreach var,GRE_VERSION GRE_MILESTONE SO_VERSION DICT_DIR,-e 's,##$(var)##,$($(var)),g' )$^ > $@

build-iceweasel/%/Makefile build-xulrunner/%/Makefile:
	cd $(firstword $(subst /, ,$@)) && ../build/autoconf/make-makefile -t .. $*

override_dh_auto_configure:

stamps/prepare-configure:: stamps/dummy
	for dir in $(AUTOCONF_DIRS); do \
		for file in config.guess config.sub; do \
			sed -i '2!b;/^#/ i\exec "/usr/share/misc/'$$file'" "$$@"' $$dir/$$file; \
		done; \
	done

stamps/configure-xulrunner:: stamps/prepare-configure
	$(if $(wildcard build-xulrunner),,mkdir build-xulrunner)
	cd build-xulrunner && \
	MOZCONFIG=$(CURDIR)/debian/xulrunner.mozconfig \
	ASFLAGS="-g" \
	../configure --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr $(CONFIGURE_FLAGS) \
		--with-default-mozilla-five-home=/usr/lib/xulrunner-$(GRE_VERSION)
	sed -i '/^OS_LDFLAGS/s|=|& $(MAIN_LDFLAGS)|' build-xulrunner/config/autoconf.mk
	sed -i '/^OS_LDFLAGS/s|=|& $(JS_LDFLAGS)|' build-xulrunner/js/src/config/autoconf.mk

stamps/configure-check-xulrunner:: stamps/configure-xulrunner
# Ensure --{with,enable}-system options properly set expected variables
# according to the definitions in the mozconfig file.
	@awk -F' *# *| *$$' ' \
	BEGIN { "find $(CURDIR)/build-xulrunner -name autoconf.mk -printf \"%p \"" | getline confs } \
	$$1 ~ /system/ { \
		if (! $$2) { \
			print FILENAME ": Missing variable for",$$1; \
			error=1; \
		} else { \
			split($$2,var,"="); \
			cmd = "grep -l " var[1] " " confs; \
			cmd | getline dir; \
			sub(/\/[^\/]*$$/, "", dir); \
			cmd = "$(MAKE) -C " dir " --no-print-directory echo-variable-" var[1]; \
			cmd | getline value; \
			if (value != var[2]) { print $$1, "triggered", var[1] "=" value,"instead of",$$2; error=1 } \
		} \
	} \
	END { if (error) { exit 1 }}' debian/xulrunner.mozconfig

stamps/build-xulrunner:: stamps/configure-check-xulrunner
	dh_auto_build --parallel --builddirectory=build-xulrunner

stamps/build-xulrunner-extra:: stamps/build-xulrunner build-xulrunner/debian/extra-stuff/Makefile
	$(MAKE) -C build-xulrunner/debian/extra-stuff

stamps/configure-iceweasel:: stamps/build-xulrunner-extra
	MOZCONFIG=$(CURDIR)/debian/iceweasel.mozconfig \
	dh_auto_configure --builddirectory=build-iceweasel -- $(CONFIGURE_FLAGS) \
		--with-libxul-sdk=$(CURDIR)/build-xulrunner/dist \
		--with-system-libxul --with-system-nspr --with-system-nss
	sed -i '/^OS_LDFLAGS/s|=|& $(MAIN_LDFLAGS)|' build-iceweasel/config/autoconf.mk

stamps/build-iceweasel:: stamps/configure-iceweasel
	dh_auto_build --builddirectory=build-iceweasel

build-iceweasel/%/filelist: stamps/build-iceweasel build-iceweasel/%/Makefile
	rm -rf build-iceweasel/$*/dist
	$(MAKE) -C build-iceweasel/$* MOZ_CHROME_FILE_FORMAT=flat DIST=$(CURDIR)/build-iceweasel/$*/dist BRANDING_TEST=1
	cd build-iceweasel/$*/dist/bin && find -type f | sort > $(CURDIR)/$@

stamps/build-check-iceweasel:: build-iceweasel/browser/branding/unofficial/filelist build-iceweasel/debian/branding/filelist
# Ensure the iceweasel branding contains everything it's supposed to
	diff $^

override_dh_auto_build: stamps/build-check-iceweasel

ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
include debian/test.mk
endif

override_dh_auto_clean::
	rm -f MPL
	rm -f debian/libmozjs$(SO_VERSION).symbols.$(DEB_BUILD_ARCH)
	rm -f $(GENERATED_FILES)
	rm -rf stamps

	dh_auto_clean --builddirectory=build-iceweasel
	dh_auto_clean --builddirectory=build-xulrunner
	find . -name "*.pyc" | xargs rm -f

	for dir in $(AUTOCONF_DIRS); do \
		for file in config.guess config.sub; do \
			sed -i '2!b;/^exec "/ d' $$dir/$$file; \
		done; \
	done

override_dh_auto_install: stamps/install-iceweasel stamps/install-xulrunner

stamps/install-xulrunner::
	dh_auto_install --sourcedirectory=build-xulrunner/xulrunner/installer -- MOZ_PKG_MANIFEST=$(CURDIR)/build-xulrunner/debian/extra-stuff/packages-static

	mv debian/tmp/usr/bin/xulrunner debian/tmp/usr/bin/xulrunner-$(GRE_VERSION)

	# Fixup permissions
	find debian/tmp/usr/share debian/tmp/usr/include -type f -print0 | xargs -0 chmod 644

	# Replace some installed files by symlinks
	cd debian/tmp/usr/lib/xulrunner-devel-$(GRE_VERSION)/sdk/lib; \
		for f in *.so; do \
			rm -f $$f; ln -s /usr/lib/xulrunner-$(GRE_VERSION)/$$f $$f; \
		done
	cd debian/tmp/usr/include/xulrunner-$(GRE_VERSION)/stable; \
		for f in *; do \
			rm -f ../unstable/$$f; ln -s ../stable/$$f ../unstable/$$f; \
		done
	cd debian/tmp/usr/share/idl/xulrunner-$(GRE_VERSION)/stable; \
		for f in *; do \
			rm -f ../unstable/$$f; ln -s ../stable/$$f ../unstable/$$f; \
		done
	ln -s ../../xulrunner-$(GRE_VERSION) debian/tmp/usr/lib/xulrunner-devel-$(GRE_VERSION)/sdk/bin

	dh_auto_install --sourcedirectory=build-xulrunner/js/src -- prefix=/usr MODULE=mozjs FORCE_STATIC_LIB= SCRIPTS=
	find debian/tmp/usr/include/mozjs -type f -printf %P\\n | while read f; do \
		file=$$(echo debian/tmp/usr/include/xulrunner-$(GRE_VERSION)/*/$$(basename $$f)); \
		rm $$file; \
		ln -s /usr/include/mozjs/$$f $$file; \
	done
	for f in /usr/include/nspr/* /usr/include/nss/*; do \
		ln -s $$f debian/tmp/usr/include/xulrunner-$(GRE_VERSION)/stable/$$(basename $$f); \
		ln -s $$f debian/tmp/usr/include/xulrunner-$(GRE_VERSION)/unstable/$$(basename $$f); \
	done
	for h in $$(grep -l -r EXPORTS build-xulrunner/media | grep Makefile$ | \
		while read f; do $(MAKE) --no-print-directory -C $$(dirname $$f) echo-variable-EXPORTS; done); do \
		rm -f debian/tmp/usr/include/xulrunner-$(GRE_VERSION)/unstable/$$h; \
	done

	rm debian/tmp/usr/lib/xulrunner-$(GRE_VERSION)/libmozjs.so
	mv debian/tmp/usr/bin/js debian/tmp/usr/bin/smjs

	sed -i '/^Cflags/ s,$${includedir}/stable,/usr/include/mozjs,' debian/tmp/usr/lib/pkgconfig/mozilla-js.pc

stamps/install-iceweasel::
	dh_auto_install --builddirectory=build-iceweasel -- installdir=$(LIB_DIR)
	chmod 755 debian/iceweasel-xremote-client

MPL: LICENSE
	cp -f $< $@

override_dh_installdocs: MPL
	dh_installdocs -A $^

stamps/dh_install:: debian/dh/dh_xulrunner debian/noinstall build-xulrunner/dist/bin/npapi_getinfo
	awk '{print "debian/tmp/" $$1 }' < debian/noinstall | xargs rm -r
	dh_install --fail-missing
#Install helpers
	install -m 755 debian/iceweasel-runner \
		debian/iceweasel/$(LIB_DIR)/iceweasel

# Install icons
	install -d -m 755 debian/iceweasel/usr/share/icons/hicolor/16x16/apps
	install -m 644 build-iceweasel/debian/branding/default16.png \
		debian/iceweasel/usr/share/icons/hicolor/16x16/apps/iceweasel.png
	install -d -m 755 debian/iceweasel/usr/share/icons/hicolor/32x32/apps
	install -m 644 build-iceweasel/debian/branding/default32.png \
		debian/iceweasel/usr/share/icons/hicolor/32x32/apps/iceweasel.png
	install -d -m 755 debian/iceweasel/usr/share/icons/hicolor/64x64/apps
	install -m 644 build-iceweasel/debian/branding/default64.png \
		debian/iceweasel/usr/share/icons/hicolor/64x64/apps/iceweasel.png
	install -d -m 755 debian/iceweasel/usr/share/icons/hicolor/scalable/apps
	install -m 644 debian/branding/iceweasel_icon.svg \
		debian/iceweasel/usr/share/icons/hicolor/scalable/apps/iceweasel.svg

# Remove unneeded configs
	rm -f debian/iceweasel/$(SHARE_DIR)/defaults/pref/firefox-l10n.js

# Install vendor preferences
	install -m 644 debian/vendor.js \
		debian/iceweasel/$(SHARE_DIR)/defaults/preferences/vendor.js

# Add Debian package version to preferences
	echo "pref(\"general.useragent.extra.firefoxComment\",\"(like Firefox/$(UPSTREAM_VERSION))\");" \
		>> debian/iceweasel/$(SHARE_DIR)/defaults/preferences/vendor.js

	sed -i 's/\(MinVersion=$(GRE_VERSION)\).*/\1/;s/\(MaxVersion=$(GRE_VERSION)\).*/\1.*/' debian/iceweasel/$(LIB_DIR)/application.ini

CMP_AWK := '$$0 !~ /^\t/ { txt = txt ? txt "\n" $$0 : $$0 } END { if (txt != expected) { print "Expected:\n" expected "\nGot:\n" txt; exit 1 }}'

stamps/check-dh_xulrunner-glue:: stamps/dh_install debian/dh/dh_xulrunner
	# Make sure dh_xulrunner is able to spot the current XPCOM standalone glue.
	perl debian/dh/dh_xulrunner_test -pxulrunner-$(GRE_VERSION) | awk -v expected='addsubstvar("xulrunner-$(GRE_VERSION)", "shlibs:Depends", "xulrunner-$(GRE_VERSION)");' $(CMP_AWK)

stamps/check-dh_xulrunner-npapi:: stamps/dh_install debian/dh/dh_xulrunner build-xulrunner/dist/bin/npapi_getinfo
	$(if $(wildcard build-xulrunner/tmp/usr/lib/mozilla),,mkdir -p build-xulrunner/tmp/usr/lib/mozilla/)
	$(if $(wildcard build-xulrunner/tmp/usr/lib/mozilla/plugins),,ln -s $(CURDIR)/build-xulrunner/dist/bin/plugins build-xulrunner/tmp/usr/lib/mozilla)
	PATH=build-xulrunner/dist/bin:$(PATH) perl debian/dh/dh_xulrunner_test -piceweasel -Pbuild-xulrunner/tmp | awk -v expected='addsubstvar("iceweasel", "npapi:Mimetypes", "application/x-print-unix-nsplugin, application/x-test");' $(CMP_AWK)

override_dh_install: stamps/check-dh_xulrunner-glue stamps/check-dh_xulrunner-npapi

override_dh_strip:
	dh_strip -a -Niceweasel -Nlibmozjs$(SO_VERSION) -Nspidermonkey-bin --dbg-package=xulrunner-$(GRE_VERSION)-dbg
	dh_strip -piceweasel --dbg-package=iceweasel-dbg
	dh_strip -plibmozjs$(SO_VERSION) --dbg-package=libmozjs$(SO_VERSION)-dbg
	dh_strip -pspidermonkey-bin

override_dh_makeshlibs:
	if [ "`$(MAKE) --no-print-directory -C build-xulrunner/js/src echo-variable-ENABLE_JIT`" = 1 ]; then \
		echo '#include "libmozjs$(SO_VERSION).symbols.jit"' > debian/libmozjs$(SO_VERSION).symbols.$(DEB_BUILD_ARCH); \
	fi
	dh_makeshlibs -plibmozjs$(SO_VERSION) -V 'libmozjs$(SO_VERSION) (>= 1.9.1.4)' -- $(GENSYMBOLS_FLAGS)

override_dh_shlibdeps:
	dh_shlibdeps -a -l$(CURDIR)/debian/tmp/usr/lib/xulrunner-$(GRE_VERSION) -Xlibmozgnome -Xlibnkgnomevfs -Xlibdbusservice
	LD_LIBRARY_PATH=$(CURDIR)/debian/tmp/usr/lib/xulrunner-$(GRE_VERSION) dpkg-shlibdeps -Tdebian/xulrunner-$(GRE_VERSION).substvars -dDepends -pgnome $(foreach lib,dbusservice mozgnome nkgnomevfs,debian/xulrunner-$(GRE_VERSION)/usr/lib/xulrunner-$(GRE_VERSION)/components/lib$(lib).so)

override_dh_gencontrol:
	dh_gencontrol -piceweasel -piceweasel-dbg
	dh_gencontrol -Niceweasel -Niceweasel-dbg -- -v$(GRE_MILESTONE)-$(DEBIAN_RELEASE)

install binary binary-arch binary-indep: $(GENERATED_FILES)

binary binary-arch binary-indep build clean install:
	dh $@

.PHONY: build clean binary-indep binary-arch binary install

.NOTPARALLEL:

$(shell awk -F: '$$1 ~ /^stamps\// { print $$1 }' debian/rules) stamps/dummy::
	@mkdir -p stamps
	$(if $(wildcard $@),,touch $@)
endif
