#!/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_BUILD_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH)

# 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

ORIG_TARBALL_COMPRESSION ?= xz# bzip2, gzip, lzma, xz
WRAPPED_TARBALL_COMPRESSION ?= none# bz2, gz, lzma, xz, none
ifneq (,$(findstring Ubuntu,$(DEBIAN_DIST)))
 ifneq (,$(findstring 10.04,$(DEBIAN_DIST)))
BINARY_PACKAGE_COMPRESSION ?= bzip2# bzip2, gzip, lzma, xz, none
 else
BINARY_PACKAGE_COMPRESSION ?= xz# bzip2, gzip, lzma, xz, none
 endif
else
BINARY_PACKAGE_COMPRESSION ?= xz# bzip2, gzip, lzma, xz, none
endif
WANT_DEBUG       := 0
WANT_SYSTEM_LIBS ?= 0
WANT_SHARED_LIBS ?= 0
WANT_SANDBOXING  ?= 1
USE_SYSTEM_V8    ?= 0
VERBOSE          ?= 0
PROCESSORS       ?= $(shell grep -ic ^processor /proc/cpuinfo)
ifeq (0,$(PROCESSORS))
PROCESSORS := 1
endif

# Enable the hardening wrapper (See https://wiki.ubuntu.com/Security/HardeningWrapper)
# Don't do it on {hardy,jaunty}+amd64 as it doesn't build for nacl on amd64
# Don't do it on maverick/armel either for now, it fails to link
# Don't do it on lucid/armel either, it crashes: LP #716703
ifeq (armel,$(DEB_BUILD_ARCH))
ifeq (,$(filter 10.04 10.10 11.04,$(DEBIAN_DIST_VERSION)))
export DEB_BUILD_HARDENING=1
else
$(warning ## Not enabling DEB_BUILD_HARDENING on Ubuntu 10.04+ armel. See LP #641126 and LP #716703)
endif
else
ifeq (,$(filter 8.04 9.04,$(DEBIAN_DIST_VERSION)))
export DEB_BUILD_HARDENING=1
else
ifneq (amd64,$(DEB_BUILD_ARCH))
export DEB_BUILD_HARDENING=1
else
$(warning ## Not enabling DEB_BUILD_HARDENING on Ubuntu 8.04/9.04 amd64)
endif
endif
endif
$(warning ## DEB_BUILD_HARDENING=$(DEB_BUILD_HARDENING))

# Disable SSE2
GYP_DEFINES = disable_sse2=1

# Build the launchpad translations (already landed upstream)
GYP_DEFINES += use_third_party_translations=1
# Also merges the newer translations from launchpad
WANT_LP_TRANSLATIONS_IN_BUILD ?= 0

## Policy: 2012-10-30, cm,kv,cc, disabling merging of LP translations. "0"
MERGE_LP_TRANSLATIONS_IN_TARBALL = 0
## Rationale: Instead of merging other stuff before "orig" (!) tarball
## creation, let's export translation templates to Launchpad, and send them
## upstream to be included in the real orig source.  It's slower for circuit,
## but all users win, and is less buggy for us.
##

# Only keep -Werror when building for the Debian or Ubuntu development branches
ifeq (,$(filter unstable development,$(DEBIAN_DIST)))
GYP_DEFINES += werror=$(NULL)
endif

# 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

ifneq (,$(findstring armhf,$(DEB_BUILD_ARCH)))
GYP_DEFINES += \
	v8_use_arm_eabi_hardfloat=true \
	arm_float_abi=hard \
	$(NULL)
endif

ifneq (,$(findstring arm,$(DEB_BUILD_ARCH)))
GYP_DEFINES += \
	arm_thumb=1 \
	arm_neon=0 \
	arm_fpu=vfpv3-d16 \
	target_arch=arm \
	disable_nacl=1 \
	linux_use_tcmalloc=0 \
	use_libjpeg_turbo=0 \
	use_cups=0 \
	$(NULL)
ifneq (,$(filter 10.10 11.04 11.10 12.04 12.10 unstable development,$(DEBIAN_DIST)))
# on $(DEB_BUILD_ARCH) and $(DEBIAN_DIST), enforce an armv7 with thumb build (or not)
GYP_DEFINES += \
	armv7=1 \
	$(NULL)
endif
else
ifeq (amd64,$(DEB_BUILD_ARCH))
GYP_DEFINES += target_arch=x64
else
ifeq (i386,$(DEB_BUILD_ARCH))
GYP_DEFINES += target_arch=ia32
else
$(warning unsupported target arch $(DEB_BUILD_ARCH) - continuing anyway)
endif
endif
endif

# 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
BUILD_ARGS += SYMBOLS=1
endif
BUILD_ARGS += BUILDTYPE=$(BUILD_TYPE)

# Verbose?
ifeq (1,$(VERBOSE))
BUILD_ARGS += V=1
endif

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

# Use upstream build flags (defined in build/common.gypi)
BUILD_ARGS += CFLAGS="" CXXFLAGS="" CPPFLAGS="" LDFLAGS=""

CC_VERSION   := $(shell gcc -dumpversion | cut -d. -f-2)

# Set this to use gcc 4.6 instead of 4.7
AVOID_GCC_47 ?= 0
ifeq (4.7,$(CC_VERSION))
GYP_DEFINES += werror=$(NULL)
ifeq (1,$(AVOID_GCC_47))
CC  := gcc-4.6
CXX := g++-4.6
BUILD_ARGS += CC=$(CC) CXX=$(CXX) CC.host=$(CC) CXX.host=$(CXX) LINK.host=$(CXX)
endif
endif

# Set this to use gcc 4.5 instead of 4.6
AVOID_GCC_46 ?= 0
  
ifeq (4.6,$(CC_VERSION))
GYP_DEFINES += werror=$(NULL)
ifeq (1,$(AVOID_GCC_46))
CC  := gcc-4.5
CXX := g++-4.5
BUILD_ARGS += CC=$(CC) CXX=$(CXX) CC.host=$(CC) CXX.host=$(CXX) LINK.host=$(CXX)
endif
endif
 
# See http://code.google.com/p/chromium/issues/detail?id=49533
ifeq (4.5,$(CC_VERSION))
GYP_DEFINES += werror=$(NULL)
endif

ifeq (bzip2,$(ORIG_TARBALL_COMPRESSION))
 ORIG_TAR_EXT   := bz2
 ORIG_TAR_FLAGS := --bzip2
else ifeq (gzip,$(ORIG_TARBALL_COMPRESSION))
 ORIG_TAR_EXT   := gz
 ORIG_TAR_FLAGS := --gzip
 DEB_TARBALL = $(wildcard *.tar.bz2 *.tar.$(ORIG_TAR_EXT))
else ifeq (lzma,$(ORIG_TARBALL_COMPRESSION))
 ORIG_TAR_EXT   := lzma
 ORIG_TAR_FLAGS := --lzma
 DEB_TARBALL = $(wildcard *.tar.bz2 *.tar.$(ORIG_TAR_EXT))
else ifeq (xz,$(ORIG_TARBALL_COMPRESSION))
 ORIG_TAR_EXT   := xz
 ORIG_TAR_FLAGS := --xz
 DEB_TARBALL = $(wildcard *.tar.bz2 *.tar.$(ORIG_TAR_EXT))
else
 $(error Invalid ORIG_TARBALL_COMPRESSION $(ORIG_TARBALL_COMPRESSION), expected bz2, gz, lzma, or xz)
endif

ifeq (gzip,$(WRAPPED_TARBALL_COMPRESSION))
 WRAPPED_TAR_EXT   := gz
 WRAPPED_TAR_FLAGS := --gzip
else ifeq (bzip2,$(WRAPPED_TARBALL_COMPRESSION))
 WRAPPED_TAR_EXT   := bz2
 WRAPPED_TAR_FLAGS := --bzip2
else ifeq (xz,$(WRAPPED_TARBALL_COMPRESSION))
 WRAPPED_TAR_EXT   := xz
 WRAPPED_TAR_FLAGS := --xz
else ifeq (lzma,$(WRAPPED_TARBALL_COMPRESSION))
 WRAPPED_TAR_EXT   := lzma
 WRAPPED_TAR_FLAGS := --lzma
else ifeq (none,$(WRAPPED_TARBALL_COMPRESSION))
else
 $(error Invalid WRAPPED_TARBALL_COMPRESSION $(WRAPPED_TARBALL_COMPRESSION), expected bz2, gz, lzma, xz, or none)
endif

post-patches::
	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 \
	$(NULL)

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 \
	$(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

ifneq (,$(filter 12.10 unstable development,$(DEBIAN_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

USE_SYSTEM_SQLITE := $(shell pkg-config 'sqlite3 >= 3.6.1' && echo 1 || echo 0)
USE_SYSTEM_SQLITE := 0

ifneq (,$(filter 8.10 9.04,$(DEBIAN_DIST)))
# Don't build with system zlib on Intrepid/Jaunty. See http://crbug.com/38073
GYP_DEFINES += use_system_zlib=0
endif

# System libs
ifeq (1,$(WANT_SYSTEM_LIBS))
GYP_DEFINES += \
	use_system_bzip2=1 \
	use_system_libjpeg=1 \
	use_system_libpng=1 \
	use_system_sqlite=$(USE_SYSTEM_SQLITE) \
	use_system_libxml=0 \
	use_system_libxslt=1 \
	$(NULL)
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 \
	chromedriver \
	$(NULL)

ifeq (1,$(WANT_SANDBOXING))
GYP_DEFINES += \
	linux_sandbox_path=/$(LIB_DIR)/$(DEBIAN_NAME)-sandbox \
	linux_sandbox_chrome_path=/$(LIB_DIR)/$(DEBIAN_NAME) \
	$(NULL)

# needed to preserve the suid and make the sandbox happy
DEB_FIXPERMS_EXCLUDE := $(DEBIAN_NAME)-sandbox
endif

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

######
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)))
 ifeq (1,$(WANT_LP_TRANSLATIONS_IN_BUILD))
	# Apply the translations patches generated by get-orig-sources
	@(set -e ; cd src ; if [ -d translations-patches ] ; then \
	for patch in translations-patches/*.patch ; do \
	  echo "# Applying $$patch..." ; \
	  patch -p 1 < $$patch ; done ; fi )
 endif
	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 )

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) python build/gyp_chromium --no-circular-check build/all.gyp
	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:: 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)" GYP_GENERATORS=make build/gyp_chromium --depth=../src $(FFMPEG_DIR)/ffmpeg.gyp
	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-%: BUILD_ARGS += CFLAGS="" CXXFLAGS="" CPPFLAGS="" LDFLAGS=""
debian/stamp-build-ffmpeg-%: debian/stamp-configure-ffmpeg-%
	cd $(FFMPEG_SRC_DIR) ; $(MAKE) -f ffmpeg.Makefile $(BUILD_ARGS)
	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 -f debian/*-stamp debian/stamp-* debian/tmp-*
	rm -f $(subst_files) *.cdbs-config_list
	perl $(CURDIR)/debian/enable-dist-patches.pl --clean $(CURDIR)/debian/patches/series
	find $(CURDIR) \( -name \*.pyc -o -name \*.pyo \) -print -delete

# Install: there's no install rules in scons yet, do it manually
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 xvf - )
	cd debian/tmp/$(LIB_DIR) && rm -f $(INSTALL_EXCLUDE_FILES)
	# Launcher script
	mkdir -p debian/tmp/usr/bin
	cp -a debian/$(DEBIAN_NAME).sh debian/tmp/usr/bin/$(DEBIAN_NAME)
	chmod 755 debian/tmp/usr/bin/$(DEBIAN_NAME)
	# Preferences
	mkdir -p debian/tmp/etc/$(DEBIAN_NAME)
	cp -a 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/$(LIB_DIR)/chrome debian/tmp/$(LIB_DIR)/$(DEBIAN_NAME)
	mv debian/tmp/$(LIB_DIR)/chrome_sandbox debian/tmp/$(LIB_DIR)/$(DEBIAN_NAME)-sandbox
	# Manpage
	mv debian/tmp/$(LIB_DIR)/chrome.1 debian/tmp/$(LIB_DIR)/chromium-browser.1
	dh_installman -pchromium-browser debian/tmp/$(LIB_DIR)/chromium-browser.1
	rm -f debian/tmp/$(LIB_DIR)/chromium-browser.1
	# chromedriver
	mkdir -p debian/$(DEBIAN_DRIVER_NAME)/$(LIB_DIR)
	cp -a debian/tmp/$(LIB_DIR)/chromedriver $(CURDIR)/debian/$(DEBIAN_DRIVER_NAME)/$(LIB_DIR)

binary-install/$(DEBIAN_NAME)::
	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 16 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
ifeq (1,$(WANT_SANDBOXING))
	chmod 4755 $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/$(DEBIAN_NAME)-sandbox
else
	rm -vf $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/$(DEBIAN_NAME)-sandbox
endif
	# 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
	cd $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/locales && \
	  rm -f $(filter-out en-US.pak,$(notdir $(wildcard $(CURDIR)/debian/$(DEBIAN_NAME)/$(LIB_DIR)/locales/*)))
	# DEB_ARCH_PACKAGES=$(DEB_ARCH_PACKAGES)
	# DEB_INDEP_PACKAGES=$(DEB_INDEP_PACKAGES)
ifneq (i386,$(DEB_BUILD_ARCH_CPU))
	# DEB_BUILD_ARCH_CPU=$(DEB_BUILD_ARCH_CPU)
	# We assume we're *not* doing the "Architecture: all" packages so we need
	# to drop the -l10n files from debian/tmp to make 'compare' happy
	cd $(CURDIR)/debian/tmp/$(LIB_DIR)/locales && \
	  rm $(filter-out en-US.pak,$(notdir $(wildcard $(CURDIR)/debian/tmp/$(LIB_DIR)/locales/*)))
endif

binary-install/$(DEBIAN_NAME)-l10n::
	rm $(CURDIR)/debian/$(DEBIAN_NAME)-l10n/$(LIB_DIR)/locales/en-US.pak

# Compare
PKG_DIRS = $(addprefix debian/,$(shell grep ^Package debian/control | cut -d' ' -f2))

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

compare:
	# 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 ; \
	else \
	  echo " => No duplicate found" ; \
	fi
	# Find missing
	@find $(PKG_DIRS) -type f -print | grep -v /DEBIAN/ | grep -vE '(/usr/lib/debug|/locales/|/inspector/|libffmpegsumo.so)' | \
	  grep $(LIB_DIR) | cut -d/ -f5- | sort > /tmp/pkg-$$$$.indebs ; \
	find debian/tmp/$(LIB_DIR) -type f -print | cut -d/ -f5- | grep -vE '(\.log$$|/locales/|/inspector/|resources/extension/demo)' | sort > /tmp/pkg-$$$$.inhammer ; \
	diff -u /tmp/pkg-$$$$.inhammer /tmp/pkg-$$$$.indebs ; \
	if [ $$? -eq 0 ] ; then \
	  echo " => All fine" ; \
	else \
	  echo " => Found differences, please investigate" ; \
	  exit 1 ; \
	fi ; \
	rm -f /tmp/pkg-$$$$.inhammer /tmp/pkg-$$$$.indebs

###############################################################################################

# Tarball (get-orig-source & get-current-source)
GCLIENT_URL  := http://src.chromium.org/svn/trunk/tools/depot_tools
CHROMIUM_URL := http://src.chromium.org/svn/trunk/src
CHROMIUM_RLZ := http://src.chromium.org/svn/releases
DEPS_URL     := http://src.chromium.org/svn/trunk/deps/third_party
GREEN_REV_URL := http://chromium-status.appspot.com/lkgr
CHANNELS_URL  := http://omahaproxy.appspot.com/all

TRANSLATIONS_TOOLS_BRANCH  := lp:~chromium-team/chromium-browser/chromium-translations-tools.head
TRANSLATIONS_EXPORT_BRANCH := lp:~chromium-team/chromium-browser/chromium-translations-exports.head
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 \
	$(NULL)
OTHER_GRIT_TEMPLATES := \
	ui/base/strings/app_locale_settings.grd \
	chrome/app/resources/locale_settings.grd \
	chrome/app/resources/locale_settings_linux.grd \
	$(NULL)
MAPPED_GRIT_TEMPLATES := \
	--map-template-names ui/base/strings/ui_strings.grd=ui/base/strings/app_strings.grd \
	$(NULL)

# New langs with enough coverage to land in official builds
# (leave empty to accept all new lang)
GRIT_WHITELISTED_LANGS ?= \
	ca@valencia \
	eu \
	gl \
	ug \
	$(NULL)

GRIT_CONVERTER_FLAGS := \
	--create-patches translations-patches \
	--import-gettext ../translations-export \
	--export-grit ../translations-grit \
	--build-gyp-file build/common.gypi \
	--other-grd-files $(shell echo $(OTHER_GRIT_TEMPLATES) | tr ' ' ',') \
	$(MAPPED_GRIT_TEMPLATES) \
	$(NULL)
	
ifeq (1,$(WANT_ONLY_WHITELISTED_NEW_LANGS))
GRIT_CONVERTER_FLAGS += --whitelisted-new-langs $(shell echo $(GRIT_WHITELISTED_LANGS) | tr ' ' ',')
endif

# See Staying Green More Of The Time at http://dev.chromium.org/developers/how-tos/get-the-code
USE_GREEN_REV ?= 0

STRIP_TARBALL ?= 1

STRIPPED_DIRS_FROM_CO := \
	src/breakpad/src \
	src/chrome/tools/test/reference_build \
	src/chrome/tools/test/reference_build/chrome_linux \
	src/webkit/data/layout_tests/LayoutTests \
	src/third_party/WebKit/LayoutTests \
	src/third_party/ffmpeg/binaries/chromium/linux/ia32 \
	src/third_party/ffmpeg/binaries/chromium/linux/ia32_dbg \
	src/third_party/ffmpeg/binaries/chromium/linux/x64 \
	src/third_party/ffmpeg/binaries/chromium/linux/x64_dbg \
	$(NULL)

# stuff we don't have access to and shouldn't be in DEPS
STRIPPED_DIRS_FROM_CO += \
	src/chrome/app/theme/google_chrome \
	src/chrome/installer/linux \
	$(NULL)

# prefix with _ those that we can't remove (just yet) because of the gclient
# hooks (see build/all.gyp) or of some unneeded deps/includes
STRIPPED_DIRS := \
	chrome/test/data/safe_browsing/old \
	chrome/test/data/firefox2_nss_mac \
	chrome/third_party/wtl/ \
	gears \
	google_update \
	o3d \
	third_party/boost \
	third_party/bsdiff \
	third_party/bspatch \
	third_party/ffmpeg/binaries \
	third_party/fuzzymatch \
	third_party/gles_book_examples \
	third_party/gold \
	third_party/hunspell/dictionaries \
	third_party/icu/mac \
	third_party/lcov \
	third_party/lighttpd \
	third_party/nspr \
	third_party/nss \
	third_party/ocmock \
	third_party/pthread \
	third_party/pyftpdlib \
	third_party/simplejson \
	third_party/scons \
	_third_party/tcmalloc \
	tools/symsrc \
	tools/site_compare \
	tools/stats_viewer \
	tools/valgrind \
	tools/wine_valgrind \
	v8/test/cctest \
	webkit/data/layout_tests \
	$(NULL)

# There are directories we want to strip, but that are unnecessarily required by the build-system
# So we drop everything but the gyp/gypi files and README.chromium (to see what that dir contained)
ALMOST_STRIPPED_DIRS := \
	courgette \
	third_party/gles2_book \
	third_party/openssl \
	$(NULL)

ifeq (1,$(WANT_SYSTEM_LIBS))
# Directories that will be dropped if the corresponding system lib are enabled in GYP_DEFINES
# We need to keep some files (like *.gyp) so we can't use STRIPPED_DIRS
# We can't drop third_party/zlib because we don't have contrib/minizip/*zip.h, and
# third_party/sqlite because it's a conditional build (see USE_SYSTEM_SQLITE)
STRIPPED_SYSTEM_LIB_DIRS += \
	third_party/bzip2 \
	third_party/libjpeg \
	third_party/libpng \
	third_party/libxslt \
	$(NULL)
endif

STRIP_SYSTEM_DIRS = \
	($(foreach DIR,$(1),$(if $(findstring use_system_$(notdir $(DIR))=1,$(GYP_DEFINES)),\
	  (cd $(2)/$(dir $(DIR)) && \
	  find $(notdir $(DIR)) -depth -mindepth 1 \! \( -name \*.gyp -o -name \*.gypi -o -name README.chromium -o -name \*.patch \) -print -delete );)))

ALMOST_STRIP_DIRS = \
	($(foreach DIR,$(1),(cd $(2)/$(dir $(DIR)) && \
	  find $(notdir $(DIR)) -depth -mindepth 1 \! \( -name \*.gyp -o -name \*.gypi -o -name README.chromium \) -print -delete );))

TMP_DDIR     := $(DEBIAN_NAME)-$(shell echo $$$$)
ifeq (,$(LOCAL_BRANCH))
TMP_DIR      := $(TMP_DDIR)
else
TMP_DIR      := $(LOCAL_BRANCH)
endif

get-orig-source: REVISION = $(NULL)
get-orig-source: TAG      = $(NULL)
ifneq (,$(DEBIAN_TAG))
get-orig-source: TAG      = $(DEBIAN_TAG)
else
ifneq (,$(DEBIAN_REV))
get-orig-source: REVISION = --revision src@$(DEBIAN_REV)
else
# Doing either the dev or beta or stable channel
ifneq (,$(CHANNEL))
ifneq (,$(filter-out stable beta dev Stable Beta Dev,$(CHANNEL)))
# Assume it's a version
get-orig-source: VERS          = $(CHANNEL)
else
get-orig-source: VERS          = $(shell wget -qO - $(CHANNELS_URL) | grep -i '^linux,$(CHANNEL)' | cut -d, -f3)
endif
get-orig-source: CHROMIUM_URL  = $(CHROMIUM_RLZ)/$(VERS)
get-orig-source: USE_GREEN_REV = 0
endif
endif
endif
get-orig-source: gos-all

get-current-source: TAG      = $(NULL)
get-current-source: REVISION = --revision src@$(DEBIAN_REVISION)
ifneq (,$(DEBIAN_REV))
get-current-source: REVISION = --revision src@$(DEBIAN_REV)
endif
get-current-source: gos-all

gos-all: gos-co gos-pack
gos-co: GCLIENT_UPDATE_FLAGS = --nohooks --delete_unversioned_trees $(REVISION)
gos-co:
ifneq (,$(CHANNEL))
	@if [ Z$(VERS) = Z ] ; then \
	  echo "Error: Cannot parse $(CHANNELS_URL) to get the release version for channel $(CHANNEL)" ; \
	  exit 1 ; \
	fi
endif
ifneq (,$(TAG))
	$(error gclient doesn\'t support tags. We need to tweak CHROMIUM_URL. Abort)
endif
ifeq (,$(LOCAL_BRANCH))
	rm -rf $(TMP_DIR)
endif
	@if [ ! -d $(TMP_DIR) ] ; then echo mkdir $(TMP_DIR); mkdir $(TMP_DIR) ; fi
	@if [ ! -d $(TMP_DIR)/tools/depot_tools ] ; then \
	  echo svn co $(GCLIENT_URL) $(TMP_DIR)/tools/depot_tools ; \
	  svn co $(GCLIENT_URL) $(TMP_DIR)/tools/depot_tools ; \
	else \
	  echo svn update $(TMP_DIR)/tools/depot_tools ; \
	  svn update $(TMP_DIR)/tools/depot_tools ; \
	fi
	rm -f $(TMP_DIR)/.gclient
ifeq (1,$(USE_GREEN_REV)$(REVISION))
	cd $(TMP_DIR) && ./tools/depot_tools/gclient config $(CHROMIUM_URL) $(GREEN_REV_URL)
else
	cd $(TMP_DIR) && ./tools/depot_tools/gclient config $(CHROMIUM_URL)
endif
ifeq (1,$(STRIP_TARBALL))
ifneq (,$(STRIPPED_DIRS_FROM_CO))
	# Add exclusions in .gclient for $(STRIPPED_DIRS_FROM_CO)
	@for excl in $(STRIPPED_DIRS_FROM_CO) ; do \
	  perl -i -pe 's,("custom_deps"\s*:\s*{),$$1\n      "'$$excl'": None\,,' $(TMP_DIR)/.gclient ; \
	done
	grep -Ev '^($$|[[:blank:]]*#)' $(TMP_DIR)/.gclient
endif
endif
	# Checkout (drop the previous content and retry if gclient failed, see http://crbug.com/39954)
	cd $(TMP_DIR) && ./tools/depot_tools/gclient update $(GCLIENT_UPDATE_FLAGS) || \
	  ( rm -rf $(foreach dir,src [0-9]*,$(wildcard $(TMP_DIR)/$(dir))) ; \
	   ./tools/depot_tools/gclient update $(GCLIENT_UPDATE_FLAGS) )

	# For NaCL, run the hooks, but not the gyp ones. All one "&&"-chained
	# statement so that a failure will stop the program and be noticed.
	cd $(TMP_DIR) && SDIR=$$(grep '"name"' .gclient |cut -d\" -f4) && perl -i~ -pe 's%\[((.)python\2, (.)(?:src/build/gyp_chromium|src/build/download_nacl_toolchains.py)\3)%[\2echo\2, \2#disabled#\2, \1%' $$SDIR/DEPS && perl -i~ -pe 's%(\bsys\.executable)\b$$%(\1 or "/usr/bin/python")%' tools/depot_tools/gclient.py && ./tools/depot_tools/gclient runhooks && mv $$SDIR/DEPS~ $$SDIR/DEPS && mv tools/depot_tools/gclient.py~ tools/depot_tools/gclient.py

ifneq (,$(LOCAL_BRANCH))
	rm -rf $(TMP_DDIR)
	cp -la $(TMP_DIR) $(TMP_DDIR)
endif
ifeq (1,$(STRIP_TARBALL))
	# Strip tarball from some big directories not needed on the linux platform
	cd $(TMP_DDIR)/src && rm -rfv $(STRIPPED_DIRS) | grep -vE '/\.svn(/|.$$)' > REMOVED-stripped.txt
ifneq (,$(ALMOST_STRIPPED_DIRS))
	# Strip listed dirs almost completely (keep *.gyp and README.chromium)
	$(call ALMOST_STRIP_DIRS,$(ALMOST_STRIPPED_DIRS),$(TMP_DDIR)/src) | grep -vE '/\.svn(/|.$$)' >> $(TMP_DDIR)/src/REMOVED-stripped.txt
endif
ifneq (,$(STRIPPED_SYSTEM_LIB_DIRS))
	$(call STRIP_SYSTEM_DIRS,$(STRIPPED_SYSTEM_LIB_DIRS),$(TMP_DDIR)/src) | grep -vE '/\.svn(/|.$$)' >> $(TMP_DDIR)/src/REMOVED-stripped.txt
endif
endif
	# Remove binaries
	cd $(TMP_DDIR)/src && find . -type f \( -iname \*.exe -o -iname \*.dll -o -iname \*.pdb -o -name \*.o -o -name \*.a -o -name \*.dylib -o -name \*.so -o -name \*.so.\* \) -print -delete > ../REMOVED-bin_only.txt

	# Remove cache files and backups
	cd $(TMP_DDIR)/src && find . -type f \( -iname \*.bak -o -iname \*.orig -o -iname \*.cache -o -name \*.pyc -o -name \*.pyo \) -print -delete > ../REMOVED-ephemera.txt
	cd $(TMP_DDIR)/src && find . -type d -name autom4te.cache -print -delete >> ../REMOVED-ephemera.txt
	
	wc -l $(TMP_DDIR)/REMOVED-*.txt

gos-pack: TMP_DIR  = $(TMP_DDIR)
ifneq (,$(DEBIAN_TAG))
gos-pack: VERSION  = $(shell echo $(DEBIAN_TAG) | cut -d= -f2)
else
ifeq (,$(CHANNEL))
gos-pack: REVISION = $(shell cd $(TMP_DIR)/src && svn log --xml --limit 1 | grep -E '^( *revision=|<date>)' | tr -d '\n' | \
	             sed -e 's/.*"\([0-9]*\)".*>\(....\)-\(..\)-\(..\)T.*/\2\3\4r\1/')
gos-pack: VERSION  = $(shell cut -d= -f2 $(TMP_DIR)/src/chrome/VERSION | sed -e 's,$$,.,' | tr -d '\n' | sed -e 's/.$$//')~svn$(REVISION)
else
gos-pack: REVISION = $(shell cd $(TMP_DIR)/src && svn info | grep ^Revision: | cut -d' ' -f2)
gos-pack: VERSION  = $(shell cut -d= -f2 $(TMP_DIR)/src/chrome/VERSION | sed -e 's,$$,.,' | tr -d '\n' | sed -e 's/.$$//')
endif
endif
gos-pack:
ifneq (,$(findstring Ubuntu,$(DEBIAN_DIST)))
 ifeq (1,$(MERGE_LP_TRANSLATIONS_IN_TARBALL))
	# Merge Translations from Launchpad
	bzr export $(TMP_DIR)/translations-tools $(TRANSLATIONS_TOOLS_BRANCH)
	bzr export $(TMP_DIR)/translations-export $(TRANSLATIONS_EXPORT_BRANCH)
	( cd $(TMP_DIR)/src ; ../translations-tools/chromium2pot.py $(GRIT_CONVERTER_FLAGS) $(GRIT_TEMPLATES) )
	# Patches created:
	@( cd $(TMP_DIR)/src ; find translations-patches -type f | xargs --verbose -n 1 diffstat -p 1 )
 endif
endif
	# Pack
	if [ src != $(DEB_TAR_SRCDIR) ] ; then mv $(TMP_DIR)/src $(TMP_DIR)/$(DEB_TAR_SRCDIR) ; fi
	mv $(TMP_DIR)/tools/depot_tools $(TMP_DIR)/$(DEB_TAR_SRCDIR)/depot_tools
	find "$(TMP_DIR)" -type f \( -iname \*.bak -o -iname \*.orig -o -iname \*.cache -o -name \*.pyc -o -name \*.pyo \) -print -delete
ifneq (none,$(WRAPPED_TARBALL_COMPRESSION))
	cd $(TMP_DIR) && time tar cf $(DEBIAN_NAME)-$(VERSION)-source.tar.$(WRAPPED_TAR_EXT) $(WRAPPED_TAR_FLAGS) --exclude-vcs $(DEB_TAR_SRCDIR)
	mkdir $(TMP_DIR)/$(DEBIAN_NAME)-$(VERSION)
	mv $(TMP_DIR)/$(DEBIAN_NAME)-$(VERSION)-source.tar.$(ORIG_TAR_EXT) $(TMP_DIR)/$(DEBIAN_NAME)-$(VERSION)
	cd $(TMP_DIR) && time tar cf ../$(DEBIAN_NAME)_$(VERSION).orig.tar.$(ORIG_TAR_EXT) $(DEBIAN_NAME)-$(VERSION)
else
	mkdir $(TMP_DIR)/$(DEBIAN_NAME)-$(VERSION)
	mv $(TMP_DIR)/$(DEB_TAR_SRCDIR) $(TMP_DIR)/$(DEBIAN_NAME)-$(VERSION)
	cd $(TMP_DIR); time tar cf $(DEBIAN_NAME)_$(VERSION).orig.tar.$(ORIG_TAR_EXT) $(ORIG_TAR_FLAGS) --exclude-vcs $(DEBIAN_NAME)-$(VERSION)
	mv $(TMP_DIR)/$(DEBIAN_NAME)_$(VERSION).orig.tar.$(ORIG_TAR_EXT) .
endif
	rm -rf $(TMP_DIR)
	@echo "# Done (created `pwd`/$(DEBIAN_NAME)_$(VERSION).orig.tar.$(ORIG_TAR_EXT))"
	@ls -l $(DEBIAN_NAME)_$(VERSION).orig.tar.$(ORIG_TAR_EXT)
