#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildopts.mk

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# System clang/lld major version, as in the chromium/CEF packages. This is
# passed to gn as a literal path, clang_prefix=/usr/lib/llvm-N/bin, so it
# cannot follow the llvm-defaults metapackage: the directory has to exist.
# Pinning also keeps a change of Debian's default LLVM from turning into an
# unannounced FTBFS here. Bump it deliberately, and rebuild before pushing.
CLANG_MVERS := 23

# Map the Debian host architecture to Dart/GN cpu names (multi-arch).
ifeq ($(DEB_HOST_ARCH),amd64)
  GN_CPU := x64
else ifeq ($(DEB_HOST_ARCH),arm64)
  GN_CPU := arm64
else ifeq ($(DEB_HOST_ARCH),armhf)
  GN_CPU := arm
else ifeq ($(DEB_HOST_ARCH),armel)
  GN_CPU := arm
else ifeq ($(DEB_HOST_ARCH),riscv64)
  GN_CPU := riscv64
else ifeq ($(DEB_HOST_ARCH),i386)
  GN_CPU := x86
else
  $(error Unsupported architecture: $(DEB_HOST_ARCH))
endif

# Bootstrap seed (Dart is self-hosting; see debian/README.source).
#   normal build : the previous dart-sdk from the archive (Build-Depends),
#                  installed at /usr/lib/dart.
#   stage0 build : the dart-sdk Build-Depends is dropped by the
#                  pkg.dart-sdk.stage0 profile and the maintainer provides the
#                  documented upstream Stage-0 seed instead. Its location can be
#                  overridden with DART_STAGE0_SDK; the default is a sibling
#                  directory so it can never be confused with a packaged SDK.
DART_STAGE0_SDK ?= /usr/lib/dart-stage0
ifneq ($(filter pkg.dart-sdk.stage0,$(DEB_BUILD_PROFILES)),)
  DART_SEED := $(DART_STAGE0_SDK)
  SEED_KIND := upstream Stage-0 seed (pkg.dart-sdk.stage0 profile)
else
  DART_SEED := /usr/lib/dart
  SEED_KIND := previous dart-sdk (Build-Depends: dart-sdk)
endif

# Honour DEB_BUILD_OPTIONS=parallel=N; otherwise leave ninja to its own default.
ifneq ($(DEB_BUILD_OPTION_PARALLEL),)
  NINJA_JOBS := -j$(DEB_BUILD_OPTION_PARALLEL)
endif

BUILDDIR := out/Release

# The upstream release commit for this version, from debian/upstream-revision.
# "dart compile exe --target-arch=" downloads the cross compilation artefacts
# for the target from channels/<channel>/raw/hash/<commit>/sdk/, so with an
# empty revision file the SDK cannot cross compile at all. The value is a
# constant, so writing it does not affect reproducibility.
UPSTREAM_TAG := $(shell dpkg-parsechangelog -S Version | \
  sed -e 's/^[0-9]*://' -e 's/-[^-]*$$//' -e 's/+\(dfsg\|ds\)[0-9]*$$//')
UPSTREAM_REVISION := $(shell awk '$$1 == "$(UPSTREAM_TAG)" { print $$2 }' \
  debian/upstream-revision)

# GN args: from-source, system Debian toolchain (gn/ninja/clang/lld), no network.
export GN_DEFINES =  is_debug=false
export GN_DEFINES += is_release=true
export GN_DEFINES += is_product=false
export GN_DEFINES += target_os=\"linux\"
export GN_DEFINES += host_cpu=\"$(GN_CPU)\"
export GN_DEFINES += target_cpu=\"$(GN_CPU)\"
export GN_DEFINES += dart_target_arch=\"$(GN_CPU)\"
export GN_DEFINES += is_clang=true
export GN_DEFINES += clang_prefix=\"/usr/lib/llvm-$(CLANG_MVERS)/bin\"
export GN_DEFINES += dart_sysroot=\"\"
export GN_DEFINES += use_custom_libcxx=false
# The source package is not a git checkout, so the build cannot read the
# release commit and writes an empty revision file. debian/rules fills it in
# at install time from debian/upstream-revision; see UPSTREAM_REVISION below.
export GN_DEFINES += dart_version_git_info=false
export GN_DEFINES += verify_sdk_hash=false
# The DevTools web application is a prebuilt Flutter web bundle upstream fetches
# from CIPD; it is not source, so it is not in the orig tarball and not built
# here (see debian/patches/0003-make-prebuilt-devtools-optional.patch).
export GN_DEFINES += dart_include_devtools=false

# Do not build or install the ASan, MSan and TSan variants of the AOT and CLI
# runtimes. Each is produced by its own gn toolchain, so they were 3360 of the
# 8501 build steps and 77 MB of the 123 MB binary package. They are instrumented
# builds for debugging the VM itself and nothing in the SDK runs them; see
# debian/patches/0009-make-the-sanitizer-runtimes-optional.patch.
export GN_DEFINES += dart_include_sanitizer_runtimes=false

# Install the unstripped binaries, so that dh_strip can put the debug symbols
# in dart-sdk-dbgsym instead of them being thrown away. Since 3.14.0 upstream
# copies the already stripped binaries from exe.stripped/ into the SDK, which
# left the package with no dbgsym at all.
export GN_DEFINES += stripped_binary_prefix=\"\"

# Build the snapshots that would otherwise be app-jit as kernel snapshots.
# app-jit snapshots are produced by a training run and record whatever the JIT
# chose to optimise, which differs between builds and makes the package
# unreproducible; britney then refuses to migrate it to testing. This is the
# value upstream already uses for cross builds. It costs about 0.24 s on every
# "dart run" and nothing elsewhere, and it is meant to be dropped once
# https://github.com/dart-lang/sdk/issues/63978 removes app-jit snapshots.
export GN_DEFINES += dart_snapshot_kind=\"kernel\"

# Debian armhf is the hard-float ABI (arm-linux-gnueabihf). Upstream defaults
# armv7 to softfp, and the armhf glibc headers ship only gnu/stubs-hard.h, so
# a softfp build fails immediately on gnu/stubs-soft.h not being found.
ifeq ($(DEB_HOST_ARCH),armhf)
export GN_DEFINES += arm_float_abi=\"hard\"
endif

%:
	dh $@

override_dh_auto_configure:
	# Bootstrap seed: NOT vendored in the source tarball. The build expects a
	# working Dart at tools/sdks/dart-sdk (build/dart/dart_action.gni).
	if [ ! -x "$(DART_SEED)/bin/dart" ]; then \
	  echo "ERROR: no Dart bootstrap seed at $(DART_SEED)" >&2; \
	  echo "  expected the $(SEED_KIND)." >&2; \
	  echo "  See debian/README.source for the bootstrap model and for how to" >&2; \
	  echo "  provide the upstream Stage-0 seed on a new architecture." >&2; \
	  exit 1; \
	fi
	mkdir -p tools/sdks
	ln -sfT $(DART_SEED) tools/sdks/dart-sdk
	# System libraries (de-vendored): the bundled third_party trees are removed
	# from the orig tarball; install a stub BUILD.gn that links the system lib and
	# symlink its headers where the build resolves them (-I../../third_party).
	#   zlib -> system zlib1g-dev
	mkdir -p third_party/zlib
	cp debian/system-libs/zlib.BUILD.gn third_party/zlib/BUILD.gn
	ln -sf /usr/include/zlib.h third_party/zlib/zlib.h
	ln -sf /usr/include/zconf.h third_party/zlib/zconf.h
	#   double-conversion -> system libdouble-conversion-dev
	mkdir -p third_party/double-conversion/src
	cp debian/system-libs/double-conversion.BUILD.gn third_party/double-conversion/src/BUILD.gn
	for h in /usr/include/double-conversion/*.h; do \
	  ln -sf "$$h" third_party/double-conversion/src/; \
	done
	mkdir -p $(BUILDDIR)
	echo '$(GN_DEFINES)' | tr ' ' '\n' | sed 's/\\"/"/g' > $(BUILDDIR)/args.gn
	/usr/bin/gn gen $(BUILDDIR)

override_dh_auto_build:
	/usr/bin/ninja $(NINJA_JOBS) -C $(BUILDDIR) create_sdk \
		compile_platform_aot.dart.snapshot

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	$(BUILDDIR)/dart-sdk/bin/dart --version
	echo 'void main() => print("dart-sdk ok");' > $(BUILDDIR)/smoke.dart
	$(BUILDDIR)/dart-sdk/bin/dart run $(BUILDDIR)/smoke.dart
endif

override_dh_auto_install:
	mkdir -p debian/dart-sdk/usr/lib/dart
	cp -a $(BUILDDIR)/dart-sdk/. debian/dart-sdk/usr/lib/dart/
	mkdir -p debian/dart-sdk/usr/bin
	ln -sf ../lib/dart/bin/dart debian/dart-sdk/usr/bin/dart
	# dartdoc HTML templates link Google Fonts from the network (privacy breach);
	# drop those external <link> tags. `dart doc` still styles output locally.
	if [ -f debian/dart-sdk/usr/lib/dart/bin/resources/dartdoc/templates/_head.html ]; then \
	  sed -i '/fonts\.googleapis\.com/d; /fonts\.gstatic\.com/d' \
	    debian/dart-sdk/usr/lib/dart/bin/resources/dartdoc/templates/_head.html; \
	fi
	# highlight.pack.js is minified Highlight.js vendored without its sources; it
	# is excluded from the source package and every reference to it is removed by
	# debian/patches/0004-dartdoc-drop-vendored-minified-highlight-js.patch.
	# Fail loudly if it ever comes back.
	test ! -e debian/dart-sdk/usr/lib/dart/bin/resources/dartdoc/resources/highlight.pack.js
	! grep -rq highlight.pack.js debian/dart-sdk/usr/lib/dart/bin/resources/dartdoc/
	# Likewise for the sanitizer runtimes, which patch 0009 switches off. Fail
	# if any of them comes back, since they are 77 MB and nothing runs them.
	! ls debian/dart-sdk/usr/lib/dart/bin/*_asan \
	     debian/dart-sdk/usr/lib/dart/bin/*_msan \
	     debian/dart-sdk/usr/lib/dart/bin/*_tsan 2>/dev/null | grep -q .
	# Likewise for the prebuilt DevTools bundle, which is not in the source
	# package at all (dart_include_devtools=false, see the patch).
	test ! -e debian/dart-sdk/usr/lib/dart/bin/resources/devtools
	# The release commit, which the build left empty; see UPSTREAM_REVISION above.
	if ! echo '$(UPSTREAM_REVISION)' | grep -qxE '[0-9a-f]{40}'; then \
	  echo "ERROR: no upstream commit for $(UPSTREAM_TAG) in debian/upstream-revision" >&2; \
	  echo "  debian/scripts/get-orig-source writes that line when it builds the" >&2; \
	  echo "  orig tarball; add it by hand if the tarball was not regenerated." >&2; \
	  exit 1; \
	fi
	echo '$(UPSTREAM_REVISION)' > debian/dart-sdk/usr/lib/dart/revision

override_dh_auto_clean:
	rm -rf out
	rm -f tools/sdks/dart-sdk
	rm -rf third_party/zlib third_party/double-conversion
	# gn and the build run the in-tree python helpers, which leave __pycache__
	# directories behind; without this a second build in the same tree fails in
	# dpkg-source with "unrepresentable changes to source".
	find . -name __pycache__ -type d -prune -exec rm -rf {} +

# Dart binaries (like Go) upset dwz.
override_dh_dwz:

# Strip the real ELF VM executables (dart, dartaotruntime*, dartvm, gen_snapshot,
# wasm-opt). The AOT *.snapshot files are ELF *data* loaded at runtime by the VM
# via dlsym of well-known symbols (kDartVmSnapshotData, ...); their symbol table
# is functional, not debug info, so they must not be stripped (see
# debian/dart-sdk.lintian-overrides).
override_dh_strip:
	dh_strip --exclude=.snapshot
