#!/usr/bin/make -f

export DH_VERBOSE = 1
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

electron = electron-23
electron_version = 23.3.11

carch = $(shell dpkg-architecture -q DEB_HOST_GNU_CPU)
debarch = $(shell dpkg-architecture -q DEB_HOST_ARCH)
ifeq ($(debarch),i386)
	vscode_arch = ia32
else ifeq ($(debarch),amd64)
	vscode_arch = x64
else ifeq ($(debarch),armhf)
	vscode_arch = arm
else ifeq ($(debarch),arm64)
	vscode_arch = arm64
else ifeq ($(debarch),riscv64)
	vscode_arch = riscv64
endif

random := $(shell head /dev/urandom | md5sum | cut -c 1-32)
fake_home = /tmp/vscode-home-$(random)

hash = $(shell echo -n "https://github.com/electron/electron/releases/download/v$(electron_version)" | sha256sum | cut -c 1-64)
electron_zip = electron-v$(electron_version)-linux-$(carch).zip
cache_dir = $(fake_home)/.cache/electron/$(hash)

node_gyp_path = $(fake_home)/node-gyp

%:
	dh $@

override_dh_auto_build: export HOME = $(fake_home)
override_dh_auto_build: export PATH := $(node_gyp_path):$(PATH)
override_dh_auto_build:
	mkdir -p $(fake_home)

	# HACK: Debian's node-gyp automatically links to libnode, which is not
	# desired for Electron
	cp -r /usr/share/nodejs/node-gyp $(node_gyp_path)
	ln -sf /usr/bin/gyp $(node_gyp_path)/gyp/gyp_main.py
	old_pwd=$$PWD; \
	cd $(node_gyp_path); \
	patch -Rp1 -i $$old_pwd/debian/patches/REVERT-link-libnode.patch; \
	ln -s bin/node-gyp.js node-gyp;

	ARCH=$(vscode_arch) ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
		yarnpkg install

	# The build process wants a zipped electron, let's construct one from system electron and put it in cache.
	mkdir -p "$(cache_dir)"
	( cd "/usr/lib/$(electron)" && zip -r "$(cache_dir)/$(electron_zip)" ./ )

ifeq ($(vscode_arch),riscv64)
	# Native node extensions caused segfault or strange behaviors.
	# Confirmed for @vscode/spdlog and node-pty. Let's build all native extensions in debug mode just in case.
	# TODO: needs further investigation
	_NODE_GYP_DEBUG=1 debian/scripts/rebuild-native-node-extensions.sh \
		$(electron_version) $(carch) \
		@vscode/spdlog @parcel/watcher keytar native-is-elevated native-keymap \
		native-watchdog node-pty windows-foreground-love
else
	# keytar somehow still links to libnode after patching node-gyp. Rebuilding.
	debian/scripts/rebuild-native-node-extensions.sh $(electron_version) $(carch) keytar
endif

	# HACK: alias yarn=yarnpkg
	_tempdir=$$(mktemp -d); \
	ln -s /usr/bin/yarnpkg $$_tempdir/yarn; \
	export PATH="$$PATH:$$_tempdir"; \
	gulp --max_old_space_size=8192 \
		--openssl-legacy-provider \
		vscode-linux-$(vscode_arch)-min

override_dh_auto_install:
	mv VSCode-linux-$(vscode_arch) VSCode-linux
	dh_auto_install $@

override_dh_auto_clean:
	rm -rf VSCode-linux out-build out-vscode out-vscode-min .build $(fake_home)
	find . -name node_modules -type d -print0 | xargs -0 rm -rf
	rm -f build/.yarnrc
