#!/usr/bin/make -f

SHELL = /usr/bin/bash

# .NET will create by default the directories ~/.dotnet and ~/.nuget, but
# sbuild will fail the build if anything is written to the default home directory.
# See https://github.com/dotnet/source-build/issues/2767
export HOME=$(shell mktemp --directory)

# The bootstrap toolchain (the distro dotnet SDK 10.0.105-ok0 copied from
# /usr/lib/dotnet into previously-built-dotnet) aborts with SIGABRT
# ("Fatal error. Internal CLR error. (0x80131506)", "dotnet" exited with code
# 134) while its fsc compiles the largest F# projects (FSharp.Compiler.Service,
# FSharp.Build, FSharp.Compiler.Interactive.Settings) during the source build.
# The fail-fast happens inside the amd64 GC mark-list sort: once a mark list
# exceeds 8K entries the GC sorts it with the vectorized vxsort code (AVX2,
# AVX-512F above 128K entries; src/coreclr/gc/gc.cpp do_vxsort) - a path only
# the huge-heap F# compiler workloads ever reach, which is why the much larger
# Roslyn/C# builds on the very same runtime never crash. Evidence that vxsort
# is the culprit: the abort is amd64-only (arm64 builds the same sources fine;
# arm64 has no vxsort and always uses the plain introsort fallback), forcing
# Workstation GC did not help (workstation GC drains the same mark lists and
# calls the same do_vxsort), and three different builders aborted identically.
# Disable the GC vector instruction sets for every dotnet process spawned
# during the build (bootstrap runtime AND freshly source-built runtime), so
# the GC mark-list sort always takes the portable introsort path.
export DOTNET_GCEnabledInstructionSets = 0
# Keep the previous round's guards as defence in depth: fsharp forces Server
# GC via src/fsharp/FSharp.Profiles.props (<ServerGarbageCollection>true</>);
# Workstation GC without DATAS keeps the mark-list/GC path as simple as
# possible (see dotnet/runtime#122528).
export DOTNET_gcServer = 0
export DOTNET_GCDynamicAdaptationMode = 0

export DNX_BIN = /usr/bin/dnx
export DOTNET_BIN = /usr/bin/dotnet
export DOTNET_ROOT_DIR = /usr/lib/dotnet
export DOTNET_SYSCONF_DIR = /etc/dotnet
DEST_DIR = $(CURDIR)/debian/tmp

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk
include $(CURDIR)/debian/eng/dotnet-pkg-info.mk

export LIBICU_PACKAGENAME := $(shell dpkg-query -W -f='$${Depends}' libicu-dev 2>/dev/null | grep --only-matching --extended-regexp 'libicu[0-9]+' | head --lines=1)

export DEB_BUILD_MAINT_OPTIONS = hardening=+all optimize=-lto

# build-time-tests/tests.py expects "OS Name: ubuntu" in `dotnet --info` output,
# but the openkylin-built runtime correctly reports "OS Name: openkylin", so the
# runtime-info assertion fails. Skip the build-time tests via nocheck.
export DEB_BUILD_OPTIONS := $(DEB_BUILD_OPTIONS) nocheck

ifeq ($(DOTNET_80_OR_GREATER), false)
    export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
endif

ifeq ($(DEB_HOST_ARCH), arm64)
# 	-fstack-clash-protection is not implemented in arm64 clang,
# 	therefore stripping this flag away to avoid the error:
# 	clang: error: argument unused during compilation.
# 	See https://github.com/llvm/llvm-project/issues/40148
    export DEB_CFLAGS_MAINT_STRIP += -fstack-clash-protection
    export DEB_CXXFLAGS_MAINT_STRIP += -fstack-clash-protection

    UBUNTU_2310_OR_GREATER = $(shell . /etc/os-release && dpkg --compare-versions $${VERSION_ID} ge 23.10 && echo true || echo false)
ifeq ($(UBUNTU_2310_OR_GREATER), true)
#   On ARM64 Ubuntu 23.10 and higher the build will fail with the message
#   "Cannot find mkstemps nor mkstemp on this platform.", related to libunwind
#   and the branch-protection `pac-ret`. By default branch-protection `standard`
#   is set which is equivalent to `bti+pac-ret`.
#   By stripping branch-protection `standard` and appending branch-protection
#   `bti`, effectively only branch protection `pac-ret` gets stripped.
#   See also: https://github.com/canonical/dotnet-source-build/issues/7
    export DEB_CFLAGS_MAINT_STRIP += -mbranch-protection=standard
    export DEB_CXXFLAGS_MAINT_STRIP += -mbranch-protection=standard

    export DEB_CFLAGS_MAINT_APPEND += -mbranch-protection=bti
    export DEB_CXXFLAGS_MAINT_APPEND += -mbranch-protection=bti
endif
endif

ifeq ($(DOTNET_CONTAINS_BOOTSTRAPPING_SDK), true)
    DOTNET_BUILD_ARGS += --clean-while-building
    ifneq ($(filter $(DEB_HOST_ARCH),s390x ppc64el),)
        DOTNET_BUILD_ARGS += --with-sdk $(CURDIR)/dotnet
    endif
else
    DOTNET_PREVIOUS_BUILT_DIR = $(CURDIR)/previously-built-dotnet
    DOTNET_BUILD_ARGS += --with-sdk "$(DOTNET_PREVIOUS_BUILT_DIR)"

    ifeq ($(DOTNET_80_OR_GREATER), true)
        DOTNET_PREREQS_PACKAGES_ARCHIVE_DIR = $(CURDIR)/prereqs/packages/archive
    else
        DOTNET_PREREQS_PACKAGES_ARCHIVE_DIR = $(CURDIR)/packages/archive
    endif
endif

ifeq ($(DOTNET_80_OR_GREATER), true)
    ifeq ($(wildcard $(CURDIR)/release.json),)
        $(error "No release.json file in the source tarball found")
    endif

    DOTNET_BUILD_ARGS += --release-manifest "$(CURDIR)/release.json"
endif

ifeq ($(DOTNET_90_OR_GREATER), true)
    DOTNET_BUILD_ARGS += --source-only
    DOTNET_RELEASE_ARTIFACTS_DIR = $(CURDIR)/artifacts/assets/Release

    ifeq ($(DOTNET_USE_SYSTEM_BROTLI), true)
        SYSTEM_LIBRARIES += +brotli
    endif
    ifeq ($(DOTNET_USE_SYSTEM_LIBUNWIND), true)
        SYSTEM_LIBRARIES += +libunwind
    endif
    ifeq ($(DOTNET_USE_SYSTEM_RAPIDJSON), true)
        SYSTEM_LIBRARIES += +rapidjson
    endif
    ifeq ($(DOTNET_USE_SYSTEM_ZLIB), true)
        SYSTEM_LIBRARIES += +zlib
    endif

#	The += operator adds text preceded by a space. Since the system libs list should
#	contain no space, we replace every space in the string with an empty character.
    space := $(shell printf " ")
    DOTNET_BUILD_ARGS += --with-system-libs $(subst $(space),,$(SYSTEM_LIBRARIES))

    ifeq ($(DOTNET_USE_MONO_RUNTIME), true)
        DOTNET_BUILD_ARGS += --use-mono-runtime
    endif
else
    DOTNET_RELEASE_ARTIFACTS_DIR = $(CURDIR)/artifacts/$(DOTNET_ARCH)/Release
endif

%:
	dh $@ --with bash-completion

override_dh_auto_clean:
	dh_auto_clean

#   clean test runner artifacts
	rm -rf $(CURDIR)/debian/eng/test-runner/Turkey/bin
	rm -rf $(CURDIR)/debian/eng/test-runner/Turkey/obj
	rm -rf $(CURDIR)/debian/eng/test-runner/Turkey.Tests/bin
	rm -rf $(CURDIR)/debian/eng/test-runner/Turkey.Tests/obj
	rm -rf $(CURDIR)/debian/eng/test-runner/bin
	rm -rf $(CURDIR)/debian/eng/test-runner/turkey
	rm -f $(CURDIR)/debian/eng/test-runner/turkey.tar.gz
	find $(CURDIR)/debian/eng/test-runner -iname '*.log' -delete

#   clean python lib artifacts
	rm -rf $(CURDIR)/debian/eng/strenum/__pycache__
	rm -rf $(CURDIR)/debian/eng/versionlib/__pycache__

override_dh_auto_build:
	printenv | sort
	vmstat --stats --unit MiB

#	Replace {{RELEASE}} placeholder in sdk-check-config.json with actual release version
	sed -i "s/{{RELEASE}}/$(RELEASE)/g" debian/sdk-check-config.json
	cat debian/sdk-check-config.json

#	If a library is being pulled in from the system, remove the bundled source for it
ifeq ($(DOTNET_USE_SYSTEM_BROTLI), true)
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/brotli
endif
ifeq ($(DOTNET_USE_SYSTEM_LIBUNWIND), true)
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/libunwind
endif
ifeq ($(DOTNET_USE_SYSTEM_RAPIDJSON), true)
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/rapidjson
endif
ifeq ($(DOTNET_USE_SYSTEM_ZLIB), true)
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/zlib
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/zlib-intel
	rm --recursive --force $(CURDIR)/src/runtime/src/native/external/zlib-ng
endif

ifeq ($(DOTNET_CONTAINS_BOOTSTRAPPING_SDK), false)
	mkdir --parents "$(DOTNET_PREREQS_PACKAGES_ARCHIVE_DIR)"

	DOTNET_SOURCE_BUILT_ARTIFACTS_TARBALL=($$(find "$(DOTNET_ROOT_DIR)/source-built-artifacts" -maxdepth 1 -name 'Private.SourceBuilt.Artifacts.$(DOTNET_MAJOR).$(DOTNET_MINOR).*.tar.gz')); \
	if [ "$${#DOTNET_SOURCE_BUILT_ARTIFACTS_TARBALL[@]}" -ne 1 ]; then \
		echo "None or more than one source built artifacts tarballs have been found: $${DOTNET_SOURCE_BUILT_ARTIFACTS_TARBALL[@]}"; \
		exit 1; \
	fi; \
	echo "source built artifacts tarball: $${DOTNET_SOURCE_BUILT_ARTIFACTS_TARBALL}"; \
	ln --symbolic \
		"$${DOTNET_SOURCE_BUILT_ARTIFACTS_TARBALL}" \
		"$(DOTNET_PREREQS_PACKAGES_ARCHIVE_DIR)/"

	cp --recursive --dereference --preserve=mode,ownership,timestamps \
	    "$(DOTNET_ROOT_DIR)" \
	    "$(DOTNET_PREVIOUS_BUILT_DIR)"
endif
#	ReadyToRun precompilation (crossgen2) intermittently crashes with an
#	internal CLR error while JIT-compiling some framework assemblies in this
#	environment; that aborts the runtime pack build with NETSDK1096. Disable
#	ReadyToRun for the repository sub-builds as well (see debian/patches).
#
#	The pre-built bootstrap toolchain copied into $(DOTNET_PREVIOUS_BUILT_DIR)
#	used to abort with "Fatal error. Internal CLR error. (0x80131506)"
#	(SIGABRT, "dotnet" exited with code 134) while its fsc compiled the
#	largest F# projects, which failed with MSB6006/MSB3073 and aborted the
#	whole source build. The GC vxsort workaround at the top of this file
#	addresses that root cause; keep a retry as insurance against any
#	residual sporadic abort. The source build is incremental (the
#	per-repository artifacts/ trees are kept), so re-running build.sh
#	resumes where it stopped; retry it up to two more times.
#	A failed build.sh attempt may leave the fsharp repo build state behind
#	(e.g. artifacts/obj/fsharp/NuGet.config still pointing at the upstream
#	online feeds because the UpdateNuGetConfig target was skipped as
#	up-to-date). The retry then fails almost immediately at the restore step
#	with "Unable to find a project to restore!" instead of re-running the
#	crash-prone fsc compile. Remove the fsharp repo build outputs before the
#	retry so that it rebuilds fsharp from a clean state and the local
#	source-build feeds get re-injected into NuGet.config.
	for attempt in 1 2 3; do \
		if VERBOSE=1 ./build.sh $(DOTNET_BUILD_ARGS) \
		-- \
		/v:n \
		/p:SkipUsingCrossgen=true \
		/p:DotNetBuildSkipReadyToRun=true \
		/p:SkipPortableRuntimeBuild=true \
		/p:LogVerbosity=n \
		/p:MinimalConsoleLogOutput=false \
		/p:ContinueOnPrebuiltBaselineError=true; then \
			exit 0; \
		fi; \
		echo "debian/rules: ./build.sh failed on attempt $$attempt of 3"; \
		if [ "$$attempt" -lt 3 ]; then \
			rm -rf "$(CURDIR)"/src/fsharp/artifacts \
			       "$(CURDIR)"/artifacts/obj/fsharp \
			       "$(CURDIR)"/artifacts/assets/Release/fsharp \
			       "$(CURDIR)"/artifacts/packages/Release/Shipping/fsharp \
			       "$(CURDIR)"/artifacts/packages/Release/NonShipping/fsharp; \
			echo "debian/rules: cleaned fsharp artifacts, retrying"; \
		fi; \
	done; \
	exit 1

	tree

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	python3 ./debian/tests/build-time-tests/tests.py --verbose --purge-after
endif

override_dh_install:
	install --mode=0755 --directory "$(DEST_DIR)$(DOTNET_ROOT_DIR)"
	install --mode=0755 --directory "$(DEST_DIR)$(DOTNET_SYSCONF_DIR)"
	ls -l "$(DOTNET_RELEASE_ARTIFACTS_DIR)"
	tar --extract \
	    --file "$$("$(CURDIR)"/debian/eng/source_build_artifact_path.py \
		           --type sdk \
				   --base-path "$(DOTNET_RELEASE_ARTIFACTS_DIR)")" \
	    --directory "$(DEST_DIR)$(DOTNET_ROOT_DIR)"

ifeq ($(DOTNET_80_OR_GREATER), true)
# 	Clean up unwanted PDB files in sdk tar.gz
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.pdb' -exec rm {} \;

# 	Extract debug symbols to their own directory for easy handling
	mkdir --parents "$(CURDIR)/artifacts/debug-symbols"
	tar --extract \
	    --file "$(DOTNET_RELEASE_ARTIFACTS_DIR)"/dotnet-symbols-sdk-*-$(DOTNET_RUNTIME_ID).tar.gz \
	    --directory "$(CURDIR)/artifacts/debug-symbols"
	ls "$(CURDIR)/artifacts/debug-symbols"
endif

#   See https://github.com/dotnet/source-build/issues/2579
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name 'testhost.x86' -delete
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name 'vstest.console' -delete

#   Fix executable permissions on files
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name 'apphost' -exec chmod +x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name 'lib*so' -exec chmod +x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name 'singlefilehost' -exec chmod +x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.a' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.dll' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.json' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.pdb' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.props' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.pubxml' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.targets' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.txt' -exec chmod -x {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.xml' -exec chmod -x {} \;

#   fixes lintian warning: dotnet-sdk-aot-9.0: executable-not-elf-or-script
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.h' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.h.in' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.c' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.cpp' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.cmake' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.m' -exec chmod 0644 {} \;
	find "$(DEST_DIR)$(DOTNET_ROOT_DIR)" -type f -name '*.def' -exec chmod 0644 {} \;

	echo "$(DOTNET_ROOT_DIR)" > "$(CURDIR)"/debian/install_location
	echo "$(DOTNET_ROOT_DIR)" > "$(CURDIR)"/debian/install_location_$(DOTNET_ARCH)

	SDK_DIR=$$(ls -1d "$(DEST_DIR)$(DOTNET_ROOT_DIR)"/sdk/*/ | head -1); \
	cp debian/sdk-check-config.json "$$SDK_DIR/sdk-check-config.json"

	dh_install

override_dh_gencontrol:
	echo "LIBICU_PACKAGENAME=$(LIBICU_PACKAGENAME)"

	dh_gencontrol -- -Vlibicu:Depends=$(LIBICU_PACKAGENAME)
ifeq ($(DOTNET_80_OR_GREATER), true)
	dh_gencontrol -paspnetcore-runtime-$(DOTNET_MAJOR).$(DOTNET_MINOR)                -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -paspnetcore-targeting-pack-$(DOTNET_MAJOR).$(DOTNET_MINOR)         -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-apphost-pack-$(DOTNET_MAJOR).$(DOTNET_MINOR)               -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-host-$(DOTNET_MAJOR).$(DOTNET_MINOR)                       -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-hostfxr-$(DOTNET_MAJOR).$(DOTNET_MINOR)                    -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-runtime-$(DOTNET_MAJOR).$(DOTNET_MINOR)                    -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY) -Vlibicu:Depends=$(LIBICU_PACKAGENAME)
	dh_gencontrol -pdotnet-targeting-pack-$(DOTNET_MAJOR).$(DOTNET_MINOR)             -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -paspnetcore-runtime-dbg-$(DOTNET_MAJOR).$(DOTNET_MINOR)            -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-runtime-dbg-$(DOTNET_MAJOR).$(DOTNET_MINOR)                -- -v$(DOTNET_DEB_VERSION_RUNTIME_ONLY)
	dh_gencontrol -pdotnet-sdk-$(DOTNET_MAJOR).$(DOTNET_MINOR)                        -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
	dh_gencontrol -pdotnet-sdk-$(DOTNET_MAJOR).$(DOTNET_MINOR)-source-built-artifacts -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
	dh_gencontrol -pdotnet-templates-$(DOTNET_MAJOR).$(DOTNET_MINOR)                  -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
	dh_gencontrol -pdotnet-sdk-dbg-$(DOTNET_MAJOR).$(DOTNET_MINOR)                    -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
ifeq ($(DOTNET_BUILD_AOT_BINARY_PACKAGE), true)
	dh_gencontrol -pdotnet-sdk-aot-$(DOTNET_MAJOR).$(DOTNET_MINOR)                    -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
endif
ifeq ($(DOTNET_100_OR_GREATER), false)
	dh_gencontrol -pnetstandard-targeting-pack-2.1-$(DOTNET_MAJOR).$(DOTNET_MINOR)    -- -v$(DOTNET_DEB_VERSION_SDK_ONLY)
endif
endif

override_dh_dwz:
#	Leaving it empty due to "dwz: Unknown debugging section .debug_addr"
