#!/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-29
electron_ver = 29.4.2

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_ver)" | sha256sum | cut -c 1-64)
electron_zip = electron-v$(electron_ver)-linux-$(carch).zip
cache_dir = $(fake_home)/.cache/electron/$(hash)

node_gyp_path = $(fake_home)/node-gyp

%:
	dh $@

override_dh_auto_configure:
	sed 's|@@ELECTRON@@|$(electron)|g' debian/code.js.in > debian/code.js

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;

	# HACK: Use corepack's Yarn 1.x
	_tempdir=$$(mktemp -d); \
	ln -s /usr/share/nodejs/corepack/dist/yarn.js $$_tempdir/yarn; \
	export PATH="$$PATH:$$_tempdir"; \
	ARCH=$(vscode_arch) ELECTRON_SKIP_BINARY_DOWNLOAD=1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
		yarn 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)" ./ )

	_tempdir=$$(mktemp -d); \
	ln -s /usr/share/nodejs/corepack/dist/yarn.js $$_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
	rm -f debian/code.js
	rm -rf .yarn
