#!/usr/bin/make -f

DEBIAN_NAME		:= $(shell dpkg-parsechangelog | sed -n 's/^Source: *\(.*\)$$/\1/ p')
DEBIAN_VERSION		:= $(shell dpkg-parsechangelog | sed -n 's/^Version: *\(.*\)$$/\1/ p')
DEBIAN_UPSTREAM_VERSION	:= $(shell echo $(DEBIAN_VERSION) | sed 's/^\(.*\)-[^-]*$$/\1/')
DEBIAN_REVISION		:= $(shell echo $(DEBIAN_VERSION) | sed 's/^.*r\([^-]*\)-.*/\1/')
DEBIAN_DIST		:= $(shell lsb_release -ds | tr -d '()' |sed -e 's/\#/ /g')
DEBIAN_DIST_NAME	:= $(shell lsb_release -si |sed -e 's/\#/ /g')
DEBIAN_DIST_VERSION	:= $(shell lsb_release -sr |sed -e 's/\#/ /g')

DEBIAN_CODECS_NAME      := $(subst browser,codecs-ffmpeg,$(DEBIAN_NAME))
DEBIAN_DRIVER_NAME      := $(subst browser,chromedriver,$(DEBIAN_NAME))

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_HOST_ARCH_CPU ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_CPU)
DEB_BUILD_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH)
DEB_BUILD_ARCH_BITS ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH_BITS)

# DEB_TAR_SRCDIR has to be 'src' as this is what gyp expects :(
DEB_TAR_SRCDIR := src
SRC_DIR        := $(CURDIR)/$(DEB_TAR_SRCDIR)
LIB_DIR        := usr/lib/$(DEBIAN_NAME)
DEB_BUILDDIR   := $(SRC_DIR)
CDBS_NO_DOC_SYMLINKING := 1 # See LP #194574
KEEPALIVE      := $(CURDIR)/debian/keep-alive.sh

# Whitelist LP provided new langs only in release builds, PPAs ship them all
WANT_ONLY_WHITELISTED_NEW_LANGS ?= 0

ifneq (,$(findstring Ubuntu,$(DEBIAN_DIST)))
DISTRIBUTION=UBUNTU
UBUNTU_DIST=$(DEBIAN_DIST)
endif
BINARY_PACKAGE_COMPRESSION ?= xz

ifneq (,$(findstring Debian,$(DEBIAN_DIST)))
DISTRIBUTION=DEBIAN
endif

WANT_DEBUG       := 0

# System libs off. Rationalle: We usually want to use as many system libraries
# as possible, as a security measure. If there's a security problem in one, the
# security team can replace it in the distro and everything magically starts
# working. Chromium is an exception. It moves quickly emough that testing that
# system libraries actually work is too hard, and upstream does a pretty good
# job of fixing known security problems soon.  As long as we keep the package
# fresh, no system libs is the smarter move.
WANT_SYSTEM_LIBS ?= 0

WANT_SHARED_LIBS ?= 0
PROCESSORS       ?= $(shell grep -ic ^processor /proc/cpuinfo)
ifeq (0,$(PROCESSORS))
PROCESSORS := 1
endif

# Set up Google API keys, see http://www.chromium.org/developers/how-tos/api-keys .
# Note: these are for Ubuntu use ONLY. For your own distribution,
# please get your own set of keys.
# Permission to add API keys, from Paweł Hajdan, To chad.miller@canonical.com
# msgid: CAADNaOFSFoch68NM1SGpCTRXqmspyKQgUPUtsF7SGRsRXiHZcg@mail.gmail.com
GOOGLEAPI_APIKEY_UBUNTU := AIzaSyAQfxPJiounkhOjODEO5ZieffeBv6yft2Q
GOOGLEAPI_CLIENTID_UBUNTU := 424119844901.apps.googleusercontent.com
GOOGLEAPI_CLIENTSECRET_UBUNTU := AIienwDlGIIsHoKnNHmWGXyJ

# Always enable hardening.
export DEB_BUILD_HARDENING=1

GYP_PARAMS = 

# Disable SSE2
GYP_DEFINES = disable_sse2=1

# Build the launchpad translations (already landed upstream)
GYP_DEFINES += use_third_party_translations=1

# Always add debug symbols, and strip them when we don't want them.
#GYP_DEFINES += release_extra_cflags="-g"

# Don't fail on compilation warnings.
GYP_DEFINES += werror=$(NULL)

# We are never using a sysroot-based toolchain; override the wrong
# autodetection for arm.
GYP_DEFINES += sysroot=

# Disable NaCl until we figure out what to do with the private toolchain
GYP_DEFINES += disable_nacl=1

# do not use third_party/gold as the linker.
GYP_DEFINES += linux_use_gold_binary=0 linux_use_gold_flags=0

# enable features that we want.
GYP_DEFINES += enable_webrtc=1

# elimiate DCHECK and DLOG function calls, to save ~9MB off binary
GYP_DEFINES += logging_like_official_build=1

COMPONENT_SHARED_LIB_BUILD := 0


# Intentional configuration, not bug work-arounds.
ifeq (arm,$(DEB_HOST_ARCH_CPU))

GYP_DEFINES += \
	arm_neon=0 \
	target_arch=arm \
	use_cups=1 \
	$(NULL)

 ifeq (armel,$(DEB_HOST_ARCH))
GYP_DEFINES += \
	v8_use_arm_eabi_hardfloat=false \
	arm_float_abi=soft \
	arm_thumb=0 \
	armv7=0 \
	$(NULL)
 endif
 ifeq (armhf,$(DEB_HOST_ARCH))
GYP_PARAMS += -DUSE_EABI_HARDFLOAT 
# ARN Neon optional flag is off because it causes build errors, AND testing
# /proc/cpuinfo contents can't work with a sandbox anyway.
GYP_DEFINES += \
	arm_neon_optional=0 \
	v8_use_arm_eabi_hardfloat=true \
	arm_fpu=vfpv3-d16 \
	arm_float_abi=hard \
	arm_thumb=1 \
	armv7=1 \
	$(NULL)
 endif
endif
ifeq (amd64,$(DEB_HOST_ARCH))
GYP_DEFINES += target_arch=x64
endif
ifeq (i386,$(DEB_HOST_ARCH))
GYP_DEFINES += target_arch=ia32
endif

# Do this for every architecture. More than 4GB of memory is too much to expect
# of builders.
COMPONENT_SHARED_LIB_BUILD := 1

ifeq (1,$(COMPONENT_SHARED_LIB_BUILD))
GYP_DEFINES += component=shared_library

# SEGV on component builds, 2013-05
GYP_DEFINES += linux_use_tcmalloc=0
endif

# Webkit library is enormous. Exclude for now.
GYP_DEFINES += remove_webcore_debug_symbols=1

# Don't let dh_installinit install *.default in /etc/default
DEB_DH_INSTALLINIT_ARGS += --noscripts --onlyscripts

# Don't let scour touch the svg files
DEB_DH_SCOUR_ARGS += -Xsvg

DEB_DH_BUILDDEB_ARGS += -- -Z $(BINARY_PACKAGE_COMPRESSION)

ifeq (1,$(WANT_DEBUG))
BUILD_TYPE := Debug
else
BUILD_TYPE := Release
# Add symbols
GYP_DEFINES += linux_dump_symbols=1
endif
BUILD_ARGS += BUILDTYPE=$(BUILD_TYPE)
BUILD_ARGS += V=1

# Shared libraries
ifeq (1,$(WANT_SHARED_LIBS))
GYP_DEFINES += library=shared_library
endif

#pre-patches::
	#-mkdir src
	#cd src; tar xf ../orig.tar.* --strip-components=1

INTERNAL_TAR_PARAMS := --transform=,^[^/]*/,src/,

post-patches::
	sed -i 's^\("/usr/lib/nss"\)^/*REM \1 REM*/"/usr/lib/$(DEB_HOST_MULTIARCH)/nss"/**/^' src/crypto/nss_util.cc
	perl $(CURDIR)/debian/enable-dist-patches.pl $(DEBIAN_DIST_VERSION) $(CURDIR)/debian/patches/series

include $(CURDIR)/debian/cdbs/tarball.mk
-include /usr/share/cdbs/1/rules/patchsys-quilt.mk
-include /usr/share/cdbs/1/rules/debhelper.mk
-include /usr/share/cdbs/1/class/makefile.mk

ifneq (1,$(PROCESSORS))
BUILD_ARGS += -j$(PROCESSORS)
endif

INSTALL_EXCLUDE_DIRS = \
	obj \
	obj.target \
	obj.host \
	.deps \
	calendar_app \
	docs_app \
	gmail_app \
	pyproto \
	pseudo_locales \
	DumpRenderTree_resources \
	lib.target \
	$(NULL)

# Literal filenames to remove, rooted at debian/tmp/usr/lib/chromium-browser.
INSTALL_EXCLUDE_FILES = \
	chrome-wrapper \
	product_logo_48.png \
	libnpapi_layout_test_plugin.so \
	libnpapi_test_plugin.so \
	mksnapshot \
	ncdecode_table \
	ncdecode_tablegen \
	ssl_false_start_blacklist_process \
	protoc \
	gfx_unittests \
	linker.lock \
	genmacro \
	genmodule \
	genperf \
	genstring \
	genversion \
	re2c \
	yasm \
	libvpx_obj_int_extract \
	xdisplaycheck \
	libTestRunner.so \
	AHEM____.TTF \
	fonts.conf \
	libTestNetscapePlugIn.so \
	plugins/libTestNetscapePlugIn.so \
	ImageDiff \
	$(NULL)

# FFmpeg-mt
# Don't build it as part of chromium. Build it separately twice, once with
# the Chrome branding to gain the extra codecs, and once without branding.
# The ffmpeg_branding variable controls which codecs are built inside the sumo lib.
# By default, ffmpeg_branding equals to "Chromium" and only builds the ogg/vorbis/theora codecs.
# When set to "Chrome", it also builds aac/ac3/mpeg4audio/h264/mov/mp3
DEB_DH_SHLIBDEPS_ARGS_$(DEBIAN_CODECS_NAME) := -l$(CURDIR)/debian/$(DEBIAN_CODECS_NAME)/$(LIB_DIR)
DEB_DH_SHLIBDEPS_ARGS_$(DEBIAN_CODECS_NAME)-extra := -l$(CURDIR)/debian/$(DEBIAN_CODECS_NAME)-extra/$(LIB_DIR)
BROWSER_GYP_DEFINES += \
	proprietary_codecs=1 \
	build_ffmpegsumo=0 \
	$(NULL)
FFMPEG_MT_GYP_DEFINES = \
	use_system_vpx=0 \
	release_extra_cflags=-g \
	$(NULL)
FFMPEG_MT_STD_GYP_DEFINES   = $(NULL)
FFMPEG_MT_EXTRA_GYP_DEFINES = ffmpeg_branding=Chrome

# Precise and earlier don't set some settings.
ifeq (,$(filter 12.04%,$(UBUNRU_DIST)))
# enable compile-time dependency on gnome-keyring
GYP_DEFINES += use_gnome_keyring=1 linux_link_gnome_keyring=1
# controlling the use of GConf (the classic GNOME configuration
# and GIO, which contains GSettings (the new GNOME config system)
GYP_DEFINES += use_gconf=1 use_gio=1
endif

# System libs
ifeq (1,$(WANT_SYSTEM_LIBS))
# Causes render hangs, 2013-05 raring
#GYP_DEFINES += use_system_libpng=1
# Causes link failures. "chromium_" prefixes.  2013-05 raring
#GYP_DEFINES += use_system_sqlite=$(USE_SYSTEM_SQLITE)

# Good in raring, saucy
GYP_DEFINES += use_system_libxml=1
GYP_DEFINES += use_system_libjpeg=1
GYP_DEFINES += use_system_bzip2=1 
# v9 is good, but not available as package.
#GYP_DEFINES += use_system_v8=1

# Arcot's suggestions.  raring, saucy
GYP_DEFINES += use_system_flac=1
GYP_DEFINES += use_system_libevent=1
GYP_DEFINES += use_system_protobuf=1
GYP_DEFINES += use_system_speex=1

GYP_DEFINES += use_system_xdg_utils=1
GYP_DEFINES += use_system_yasm=1
endif

# Build everything (like All), including test programs but minus things we don't
# want (breakpad, courgette, ..) or don't need (the other small tools)
BUILD_TARGETS := \
	chrome \
	chrome_sandbox \
	base_unittests \
	automated_ui_tests \
	$(NULL)

# use system v8
ifeq (1,$(USE_SYSTEM_V8))
GYP_DEFINES += \
	javascript_engine=system-v8 \
	$(NULL)
endif

ifneq (,$(GOOGLEAPI_APIKEY_$(DISTRIBUTION)))
GYP_DEFINES += \
	google_api_key='$(GOOGLEAPI_APIKEY_$(DISTRIBUTION))' \
	google_default_client_id='$(GOOGLEAPI_CLIENTID_$(DISTRIBUTION))' \
	google_default_client_secret='$(GOOGLEAPI_CLIENTSECRET_$(DISTRIBUTION))'
else
$(warning Google API info is not set in build variables GOOGLEAPI_APIKEY_$(DISTRIBUTION) GOOGLEAPI_CLIENTID_$(DISTRIBUTION) GOOGLEAPI_CLIENTSECRET_$(DISTRIBUTION))
endif

ifneq (,$(GOOGLEAPI_APIKEY_$(DISTRIBUTION)))
GYP_PARAMS += \
	-Dgoogle_api_key='$(GOOGLEAPI_APIKEY_$(DISTRIBUTION))' -Dgoogle_default_client_id='$(GOOGLEAPI_CLIENTID_$(DISTRIBUTION))' -Dgoogle_default_client_secret='$(GOOGLEAPI_CLIENTSECRET_$(DISTRIBUTION))'
endif

ifneq ($(DEB_HOST_ARCH),$(DEB_BUILD_ARCH))
$(note Cross compiling for $(DEB_HOST_ARCH), from this $(DEB_BUILD_ARCH))
CROSS_BUILD = PKG_CONFIG_PATH=/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig:/usr/$(DEB_HOST_MULTIARCH)/lib/pkgconfig CXX=$(DEB_HOST_GNU_TYPE)-$(CXX)
DEB_MAKE_ENVVARS += CXX=$(DEB_HOST_GNU_TYPE)-$(CXX)
else
CROSS_BUILD = 
endif
BUILD_ARGS += CC_host=$(CC) CXX_host=$(CXX) 

######
DO = (touch r1; echo '$(1)'; $(1); touch r2 ; T1=`date -r r1 +%s` ; T2=`date -r r2 +%s`; echo "PERF: '$(2)' built in "`expr $$T2 - $$T1`" sec"; rm -f r1 r2;)

subst_files = \
	debian/$(DEBIAN_NAME).sh \
	$(NULL)

%:: %.in
	sed -e 's#@BUILD_DIST@#$(DEBIAN_DIST_NAME) $(DEBIAN_DIST_VERSION)#g' \
	    -e 's#@BUILD_DIST_NAME@#$(DEBIAN_DIST_NAME)#g' \
	    -e 's#@BUILD_DIST_VERSION@#$(DEBIAN_DIST_VERSION)#g' \
	    < $< > $@

pre-build:: debian/pre-build-stamp $(subst_files)

debian/pre-build-stamp:
ifneq (,$(findstring Ubuntu,$(DEBIAN_DIST)))
	sed -ri '/const PrepopulatedEngine google = \{/,/\}\;/ { s/sourceid=chrome\&/&client=ubuntu\&channel=cs\&/g; }' \
		src/chrome/browser/search_engines/template_url_prepopulate_data.cc
endif
	sed -i 's,/etc/chromium/policies,/etc/$(DEBIAN_NAME)/policies,' \
		src/chrome/common/chrome_paths.cc
	touch $@

DEB_MAKE_EXTRA_ARGS   := $(NULL)
DEB_MAKE_BUILD_TARGET := $(BUILD_ARGS) $(BUILD_TARGETS) || ( $(KEEPALIVE) stop ; exit 1 )
# There is no clean or check target in the upstream makefile
DEB_MAKE_CLEAN_TARGET :=
DEB_MAKE_CHECK_TARGET :=

configure/$(DEBIAN_NAME):: debian/configure-stamp

debian/configure-stamp: GYP_ENV = GYP_GENERATORS=make
ifneq (,$(GYP_DEFINES))
debian/configure-stamp: GYP_ENV += GYP_DEFINES="$(GYP_DEFINES) $(BROWSER_GYP_DEFINES)"
endif
debian/configure-stamp:
	cd $(SRC_DIR) && $(GYP_ENV) $(CROSS_BUILD) python build/gyp_chromium build/all.gyp $(GYP_PARAMS)
	touch $@
	# Populate the LASTCHANGE file as we no longer have the VCS
	# files at this point
	echo "LASTCHANGE=$(DEBIAN_REVISION)" > $(SRC_DIR)/build/util/LASTCHANGE
	# BUILD_ARGS=$(BUILD_ARGS)
	# Start the keep-alive script
	@chmod 755 $(KEEPALIVE)
	$(KEEPALIVE) start &

common-build-arch common-build-indep:: debian/stamp-makefile-build-perf
debian/stamp-makefile-build-perf: debian/stamp-makefile-build
	@T2=`date +%s`; T1=`date -r debian/configure-stamp +%s`; echo "PERF: '$(BUILD_TARGETS)' built in "`expr $$T2 - $$T1`" sec"
	touch $@
	$(KEEPALIVE) stop

common-build-arch:: tests
common-build-arch:: debian/stamp-build-ffmpeg-std debian/stamp-build-ffmpeg-extra

debian/stamp-configure-ffmpeg-%:
	rm -rf $(FFMPEG_SRC_DIR)/*.mk $(FFMPEG_SRC_DIR)/out
	cd $(SRC_DIR) && GYP_DEFINES="$(GYP_DEFINES)" $(CROSS_BUILD) GYP_GENERATORS=make build/gyp_chromium --depth=../src $(FFMPEG_DIR)/ffmpeg.gyp $(GYP_PARAMS)
	touch $@

debian/stamp-build-ffmpeg-%: GYP_DEFINES += $(FFMPEG_MT_$(subst std,STD,$(subst extra,EXTRA,$*))_GYP_DEFINES) $(FFMPEG_MT_GYP_DEFINES)
debian/stamp-build-ffmpeg-%: FFMPEG_DIR = third_party/ffmpeg
debian/stamp-build-ffmpeg-%: FFMPEG_SRC_DIR = $(SRC_DIR)/$(FFMPEG_DIR)
debian/stamp-build-ffmpeg-%: debian/stamp-configure-ffmpeg-%
	cd $(FFMPEG_SRC_DIR) ; $(MAKE) -f ffmpeg.Makefile $(BUILD_ARGS) $(CROSS_BUILD)
	install -d -m 755 $(CURDIR)/debian/tmp-$*/$(LIB_DIR)
	install -m 644 $(FFMPEG_SRC_DIR)/out/$(BUILD_TYPE)/libffmpegsumo.so $(CURDIR)/debian/tmp-$*/$(LIB_DIR)
	touch $@

clean::
	rm -rf debian/*-stamp debian/stamp-* debian/tmp-*
	rm -f $(subst_files) *.cdbs-config_list
	sed -i 's^/\*REM \(.*\) REM\*/.*/\*\*/^\1^' src/crypto/nss_util.cc
	perl $(CURDIR)/debian/enable-dist-patches.pl --clean $(CURDIR)/debian/patches/series
	find $(CURDIR) \( -name \*.pyc -o -name \*.pyo \) -delete
	test ! -d $(CURDIR)/src/out || rm -r $(CURDIR)/src/out

tests:: TEMPFILE=$(shell mktemp)
tests::
	# disabled: SecurityTest exhausts memory to fail
	# disabled: PowerMonitorTest doesn't mock power enough, I think
	# disabled: FileUtilTest fails because of fakeroot interaction
	# disabled: ReadOnlyFileUtilTest.ContentsEqual fakeroot
	# disabled: ReadOnlyFileUtilTest.TextContentsEqual fakeroot
	$(KEEPALIVE) start &
	cd $(SRC_DIR); ./out/$(BUILD_TYPE)/base_unittests --gtest_filter=-SecurityTest.NewOverflow:PowerMonitorTest.\*:FileUtilTest.ChangeFilePermissionsAndRead:FileUtilTest.ChangeFilePermissionsAndWrite:FileUtilTest.ChangeDirectoryPermissionsAndEnumerate:ReadOnlyFileUtilTest.ContentsEqual:ReadOnlyFileUtilTest.TextContentsEqual: |tee $(TEMPFILE) |cat -n; $(KEEPALIVE) stop
	@echo If more than 15 tests fail, then we interpret that as too poor quality to continue.
	sed -e 1,/FAILED.\*tests,\ listed\ below/d $(TEMPFILE) |grep -c \\\[\ \ FAILED\ \ \\\] |xargs test 15 -gt
	@echo Unit tests are good enough.
	#

# Populate the debian/tmp directories with things that are not constructed in
# build rules, and rename files to what we expect.  This prepares those files
# for the .install lists to pluck things out, and leaves a base to compare
# against to make sure we package up everything that we provide.
common-install-prehook-impl::
	mkdir -p debian/tmp/$(LIB_DIR)
	( cd $(SRC_DIR)/out/$(BUILD_TYPE) && tar $(foreach excl,$(INSTALL_EXCLUDE_DIRS),--exclude=$(excl)) -cf - . ) | ( cd debian/tmp/$(LIB_DIR) && tar xf - )
ifeq (1,$(COMPONENT_SHARED_LIB_BUILD))
	mkdir -p debian/tmp/$(LIB_DIR)/libs
	( cd $(SRC_DIR)/out/$(BUILD_TYPE)/lib.target && tar cf - . ) | ( cd debian/tmp/$(LIB_DIR)/libs && tar xf - )
endif
	cd debian/tmp/$(LIB_DIR) && rm -fv $(INSTALL_EXCLUDE_FILES)
	# Launcher script
	mkdir -p debian/tmp/usr/bin
	install --mode=755 debian/$(DEBIAN_NAME).sh debian/tmp/usr/bin/$(DEBIAN_NAME)
	# Preferences
	mkdir -p debian/tmp/etc/$(DEBIAN_NAME)
	install --mode=644 debian/$(DEBIAN_NAME).default debian/tmp/etc/$(DEBIAN_NAME)/default

	# Rename the binary from chrome to $(DEBIAN_NAME), this is required
	# as chromium dereferences all symlinks before starting its children
	# making the Gnome System Monitor confused with icons
	mv debian/tmp/usr/lib/chromium-browser/chrome debian/tmp/$(LIB_DIR)/$(DEBIAN_NAME)

	# Manpage is for wrong program name, and it's in a weird place.  Use and destroy.
	mv debian/tmp/$(LIB_DIR)/chrome.1 debian/tmp/$(LIB_DIR)/chromium-browser.1
	rm -v debian/tmp/$(LIB_DIR)/chromium-browser.1

	# "you have to change the underscore from the build target into a hyphen".
	# https://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
	mv debian/tmp/usr/lib/chromium-browser/chrome_sandbox debian/tmp/usr/lib/chromium-browser/chrome-sandbox

# Prepare the debian/tmp*-installed files before we distribute them into
common-install-prehook-impl::
ifeq (1,$(COMPONENT_SHARED_LIB_BUILD))
	# Set the directory for looking up component libraries.
	find debian/tmp*/usr/lib/chromium-browser/libs             -type f -name \*.so             -execdir chrpath --replace "\$$ORIGIN" {} \;
	find debian/tmp*/usr/lib/chromium-browser      -maxdepth 1 -type f -name \*.so             -execdir chrpath --replace "\$$ORIGIN/libs" {} \;
endif
	find debian/tmp*/usr/lib/chromium-browser      -maxdepth 1 -type f             -executable -execdir chrpath --replace "\$$ORIGIN/libs" {} \;


binary-install/$(DEBIAN_NAME)::
ifeq (1,$(COMPONENT_SHARED_LIB_BUILD))
	dh_install -p$(DEBIAN_NAME) debian/tmp/$(LIB_DIR)/libs $(LIB_DIR)
endif
	mkdir -p $(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/pixmaps
	cp -a src/chrome/app/theme/chromium/product_logo_48.png $(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/pixmaps/$(DEBIAN_NAME).png
	for size in 22 24 32 48 64 128 256 ; do \
	  mkdir -p $(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/icons/hicolor/$${size}x$${size}/apps ; \
	  cp -a src/chrome/app/theme/chromium/product_logo_$$size.png  \
		$(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/icons/hicolor/$${size}x$${size}/apps/$(DEBIAN_NAME).png ; \
	done
	mkdir -p $(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/icons/hicolor/scalable/apps
	cp -a $(CURDIR)/debian/$(DEBIAN_NAME).svg $(CURDIR)/debian/$(DEBIAN_NAME)/usr/share/icons/hicolor/scalable/apps
	# NaCL may be blacklisted, so only include it when it's been built
ifeq (,$(filter disable_nacl=1,$(GYP_DEFINES)))
	cp -a debian/tmp/$(LIB_DIR)/libppGoogleNaClPluginChrome.so debian/$(DEBIAN_NAME)/$(LIB_DIR)/
	cp -a debian/tmp/$(LIB_DIR)/nacl_irt_* debian/$(DEBIAN_NAME)/$(LIB_DIR)/
endif
	# Locales: only keep en-US in the main deb. This is the opposite of binary-install/$(DEBIAN_NAME)-l10n rule.
	find $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/*locales -type f -name \*.pak ! -name en-US.pak -delete

# Tke l10n .install file is far too greedy, but we don't want to list every
# language there because we don't know them all.  Remove what's are in the main
# package.
binary-install/$(DEBIAN_NAME)-l10n::
	rm -v $(CURDIR)/debian/$(DEBIAN_NAME)-l10n/$(LIB_DIR)/*locales/en-US.pak

# Compare
PKG_DIRS = $(addprefix debian/,$(shell dh_listpackages))

binary-predeb/$(DEBIAN_NAME)::
	chmod +s $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/chrome-sandbox

binary-predeb/$(DEBIAN_NAME):: compare
ifneq (,$(findstring Ubuntu,$(DEBIAN_DIST)))
	# we need space on the CD, so remove duplicates of the doc files
	# (See LP: #194574 as for why we don't let cdbs do it)
	@for doc in copyright AUTHORS changelog.Debian.gz ; do \
	  F=debian/$(DEBIAN_NAME)/usr/share/doc/$(DEBIAN_NAME)/$$doc ; \
	  for file in `find $(addsuffix /usr/share/doc,$(filter-out debian/$(DEBIAN_NAME),$(PKG_DIRS))) -type f -name $$doc -print`; do \
	    cmp -s $$file $$F ; \
	    if [ $$? -eq 0 ] ; then \
	      rm -f $$file ; \
	      echo "  symlinking $$doc in '"`echo $$file | awk 'BEGIN{ FS="/"} { print $$2 }'`"' to file in '$(DEBIAN_NAME)'" ; \
	      ( cd `dirname $$file` ; ln -s ../$(DEBIAN_NAME)/$$doc ) ; \
	    fi ; \
	  done ; \
	done
endif

# These are (leading-slash-less) files that are created by upstream builder,
# but intentionally not packaged.  The should match very specifically so we
# know they only match things we should ignore. No false negatives, plz.
# When composing a match, it has to be escaped for nonquoted shell expression
# first, then escaped for Make. No expression can contain a space, as it's
# used later to join expressions in alternation; a dot should suffice.
# Useful: https://code.google.com/p/chromium/codesearch#search/q=package:chromium
## webkit tests
#BUILT_UNUSED_MATCH  = ^usr/lib/chromium-browser/AHEM____.TTF$$
#BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/fonts.conf$$
#BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/libTestNetscapePlugIn.so$$
#BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/plugins/libTestNetscapePlugIn.so$$
#BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/ImageDiff$$
# lib.host weird extra installed files
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/lib.host/lib.*.so
## test suites that we run. No EOL to match logfiles too.
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/base_unittests
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/automated_ui_tests
## api test
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/resources/extension/demo/library.js$$
## a build-time assertion. buggy installer.
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/remoting_resources_verified.stamp$$
## xdg-utils install dep
BUILT_UNUSED_MATCH += ^usr/lib/chromium-browser/xdg-\(mime\|settings\)$$

BUILT_UNUSED_INDEP_MATCH = ^usr/lib/chromium-browser/.*locales/.\*.pak$$

PACKAGED_NOT_FROM_TREE_MATCH  = ^usr/share/applications/chromium-browser.desktop$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/apport/package-hooks/chromium-browser.py$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/chromium-browser/README.source$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/chromium-browser/TODO.Debian$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/chromium-browser/copyright.problems.gz$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/.\*/buildinfo_.\*.gz$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/gnome-control-center/default-apps/chromium-browser.xml$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/.\*/chromium-browser.png$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/.\*/chromium-browser.svg$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/.\*/copyright$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/doc/.\*/changelog.Debian.gz$$
PACKAGED_NOT_FROM_TREE_MATCH += ^usr/share/man/man1/chromium-browser.1.gz$$

# Expressions to map filenames in the comparison logic so that a rename in
# packaging is correctly handled.  No expression contains a space.  Each should
# be able to be used as a SED expression.  This changes file names in
# pre-packaging listing. All of this is done AFTER removing items
# BUILD_UNUSED_MATCH .  Quote for shell, then Make.
#  Man pages are compressed.
RENAMED_FILE  = /\\/man\\//s,\(.gz\)\?\$$,.gz,

compare: T := $(shell mktemp -d -t chromium-comparisons-XXXXXXX)
compare: SPACE := $(eval) $(eval)
compare:
	# Spanish translation is our canary for whether we have made a binary-indep
	# package or not.  It will always be "installed" to the tmp/, and yet only
	# be in the l10n package if we make binary-indep packages on this
	# architecture's builder.
	find debian -name es.pak

	# Look for duplicates, fail if we find any
	@DUPES=`find $(PKG_DIRS) -type f -print | grep -v /DEBIAN/ | cut -d/ -f3- | sort | uniq -c | grep -vE '^ *2 .*/libffmpegsumo.so$$' | grep -vE '^  *1 '` ; \
	if [ "Z$$DUPES" != Z ] ; then \
	  echo " => Found duplicates:\n $$DUPES" ; \
	  exit 1 ; \
	fi

	# Find missing.  Note the "es" translation test.  Builders may not
	# "install" to binary-indep packages if another arch builder is going to
	# make them, so we don't verify files that would go into arch:any packages.
	#
	# Additionally, it may overmatch things that are in the binary package, like
	# en-US, so we have to filter the installed package also, for now.  FIXME.
	find debian/tmp debian/tmp-extra debian/tmp-std -type f |cut -d/ -f3- |sort >$(T)/unfiltered-built
	grep -vE \($(subst $(SPACE),\|,$(BUILT_UNUSED_MATCH))\) $(T)/unfiltered-built $(foreach expr,$(RENAMED_FILE), |sed -r -e $(expr)) >$(T)/built
	find $(PKG_DIRS) -type f |grep -v /DEBIAN |cut -d/ -f3- |grep -v ^usr/lib/debug/ |sort >$(T)/unfiltered-packaged
	grep -vE \($(subst $(SPACE),\|,$(PACKAGED_NOT_FROM_TREE_MATCH))\) $(T)/unfiltered-packaged >$(T)/packaged
	test ! -f debian/chromium-browser-i10n/usr/lib/chromium-browser/locales/es.pak && echo "No arch:all packages built here, so we ignore indep files from comparison."        && mv $(T)/built    $(T)/refiltering && grep -vE \($(subst $(SPACE),\|,$(BUILT_UNUSED_INDEP_MATCH))\) $(T)/refiltering >$(T)/built
	test ! -f debian/chromium-browser-i10n/usr/lib/chromium-browser/locales/es.pak && echo "No arch:all packages built here, so we ignore accidental matches from comparison." && mv $(T)/packaged $(T)/refiltering && grep -vE \($(subst $(SPACE),\|,$(BUILT_UNUSED_INDEP_MATCH))\) $(T)/refiltering >$(T)/packaged
	if ! diff -U0 $(T)/built $(T)/packaged; then \
	  echo " => Found differences, please investigate. $(T)/built $(T)/packaged" ; \
	  exit 1; \
	fi
	for expr in $(BUILT_UNUSED_MATCH); do if ! grep -E $$expr $(T)/unfiltered-built >/dev/null; then echo "Warning: Unused built matcher: $$expr in $(T)/unfiltered-built "; fi; done
	for expr in $(PACKAGED_NOT_FROM_TREE_MATCH); do if ! grep -E $$expr $(T)/unfiltered-packaged >/dev/null; then echo "Warning: Unused packaged matcher: $$expr"; fi; done
	rm -r $(T)

###############################################################################################
# Translations

# New langs with enough coverage to land in official builds
# (leave empty to accept all new lang)
patch-translations: T := $(shell mktemp -d -t chromium-launchpad-translations-XXXXXXX)
patch-translations: GRIT_WHITELISTED_LANGS ?= ca@valencia eu gl ug 
patch-translations: TRANSLATIONS_TOOLS_BRANCH  := http://bazaar.launchpad.net/~chromium-team/chromium-browser/chromium-translations-tools.head
patch-translations: TRANSLATIONS_EXPORT_BRANCH := http://bazaar.launchpad.net/~chromium-team/chromium-browser/chromium-translations-exports.head
patch-translations: GRIT_TEMPLATES := chrome/app/chromium_strings.grd chrome/app/generated_resources.grd chrome/app/policy/policy_templates.grd ui/base/strings/ui_strings.grd webkit/glue/inspector_strings.grd webkit/glue/webkit_strings.grd
patch-translations: OTHER_GRIT_TEMPLATES := ui/base/strings/app_locale_settings.grd chrome/app/resources/locale_settings.grd chrome/app/resources/locale_settings_linux.grd 
patch-translations: MAPPED_GRIT_TEMPLATES := --map-template-names ui/base/strings/ui_strings.grd=ui/base/strings/app_strings.grd 
patch-translations: GRIT_CONVERTER_FLAGS := --create-patches translations-patches --import-gettext ../translations-export --export-grit $(T)/translations-grit --build-gyp-file build/common.gypi --other-grd-files $(shell echo $(OTHER_GRIT_TEMPLATES) | tr ' ' ',') $(MAPPED_GRIT_TEMPLATES) 
ifeq (1,$(WANT_ONLY_WHITELISTED_NEW_LANGS))
patch-translations: GRIT_CONVERTER_FLAGS += --whitelisted-new-langs $(shell echo $(GRIT_WHITELISTED_LANGS) | tr ' ' ',')
endif
patch-translations: PATCH_FILE := launchpad_translations.patch
patch-translations:
	test -d $(T)/translations-tools || bzr export $(T)/translations-tools $(TRANSLATIONS_TOOLS_BRANCH)
	test -d $(T)/translations-export || bzr export $(T)/translations-export $(TRANSLATIONS_EXPORT_BRANCH)
	cd src; $(T)/translations-tools/chromium2pot.py $(GRIT_CONVERTER_FLAGS) $(GRIT_TEMPLATES) 
	! test "$$(quilt diff)"  # if any changes outstanding, abort!
	-quilt delete "$(PATCH_FILE)"
	quilt new "$(PATCH_FILE)"
	set -eu; find translations-grit -type f |sed -e 's,^$(T)/translations-grit/,,' |while read updatedfile; do quilt add -P "$(PATCH_FILE)" src/"$$updatedfile"; cp $(T)/translations-grit/"$$updatedfile" src/"$$updatedfile"; done;
	{ echo "Description: Contributed translations from Launchpad. "; echo; } |quilt header -r "$(PATCH_FILE)"
	quilt refresh -pab --no-timestamps "$(PATCH_FILE)"
	@echo "Patch needs committing."


###############################################################################################
# Retrieve/fabricate orig tarball.
get-packaged-orig-source: gos

export ORIG_PACKAGE
export ORIG_VERSION

gos: URL=https://commondatastorage.googleapis.com/chromium-browser-official/chromium-$(ORIG_VERSION).tar.xz
gos: DEST_FILENAME=$(ORIG_PACKAGE)_$(ORIG_VERSION).orig.tar.xz
gos:
	mkdir -p $(ORIG_PACKAGE)-$(ORIG_VERSION)/src
	@set -x; wget --continue --progress=dot:mega --output-document=source.tar.xz $(URL) && tar xf source.tar.xz --exclude-backups --exclude-vcs --directory $(ORIG_PACKAGE)-$(ORIG_VERSION)/src --strip-components=1 && tar cJf $(DEST_FILENAME) $(ORIG_PACKAGE)-$(ORIG_VERSION)
	@echo "# Done (created $(CURDIR)/$(DEST_FILENAME))"

