# Template file for 'electron24'
pkgname=electron24
version=24.3.0
revision=3
_nodever=18.14.0
_chromiumver=112.0.5615.165
archs="x86_64* aarch64*"
create_wrksrc=yes
build_wrksrc="src"
hostmakedepends="$(vopt_if clang "clang lld") pkgconf perl gperf bison ninja nodejs hwids
 libwebp-devel freetype-devel harfbuzz-devel libpng-devel nss-devel which git libevent-devel
 pciutils-devel ffmpeg-devel libxml2-devel libglib-devel yarn openjdk8 libxslt-devel
 opus-devel libXcursor-devel libXcomposite-devel libXtst-devel libXrandr-devel libXScrnSaver-devel
 alsa-lib-devel re2-devel snappy-devel mit-krb5-devel $(vopt_if pulseaudio pulseaudio-devel)
 $(vopt_if sndio sndio-devel) jq python3.11"
makedepends="libpng-devel gtk+-devel gtk+3-devel nss-devel pciutils-devel
 libXi-devel libgcrypt-devel libsecret-devel cups-devel elfutils-devel
 libXcomposite-devel speech-dispatcher-devel libXrandr-devel mit-krb5-devel
 libXScrnSaver-devel alsa-lib-devel snappy-devel libdrm-devel
 libxml2-devel libxslt-devel $(vopt_if pulseaudio pulseaudio-devel) libexif-devel
 libXcursor-devel libflac-devel speex-devel libmtp-devel libwebp-devel
 libjpeg-turbo-devel libevent-devel json-c-devel harfbuzz-devel
 minizip-devel jsoncpp-devel zlib-devel libcap-devel libXdamage-devel
 re2-devel fontconfig-devel freetype-devel opus-devel libffi-devel
 $(vopt_if sndio sndio-devel) ffmpeg-devel libva-devel libuv-devel c-ares-devel libnotify-devel
 $(vopt_if pipewire pipewire-devel) wayland-devel libcurl-devel libxshmfence-devel"
short_desc="Cross platform application framework based on web technologies"
maintainer="John <me@johnnynator.dev>"
license="BSD-3-Clause"
homepage="https://electronjs.org"
distfiles="https://github.com/electron/electron/archive/v$version.tar.gz>electron-${version}.tar.gz
 https://commondatastorage.googleapis.com/chromium-browser-official/chromium-$_chromiumver.tar.xz
 https://github.com/nodejs/node/archive/v$_nodever.tar.gz>node-$_nodever.tar.gz"
checksum="3359336061436701b6eebc589559753d240bd8fb8c92d5c944563d2cbf0f6762
 168c62fea9f428f99fbf967f36a75ee5da160429e3a5b86bf02188c5fe7c79fd
 31bbccdff73269baebcc9f32c2ffe428f28be79841527c63e95da93e8c630829"

case "$XBPS_TARGET_MACHINE" in
	ppc64*-musl) makedepends+=" libucontext-devel" ;;
esac

if [ "$XBPS_LIBC" = musl ]; then
	hostmakedepends+=" musl-legacy-compat"
fi

if [ "$XBPS_TARGET_LIBC" = "musl" ]; then
	makedepends+=" musl-legacy-compat"
fi

no_generic_pkgconfig_link=yes
lib32disabled=yes
nopie=yes  # contains tools that are not PIE, enables PIE itself

build_options="pulseaudio sndio clang pipewire"
build_options_default="pulseaudio clang pipewire"

#if [ "$build_option_clang" ]; then
nocross="Yes"
#elif [ "${XBPS_TARGET_MACHINE%%-musl}" = "aarch64" ]; then
#	broken="Falls apart at runtime when compiled with gcc"
#fi

_buildtype=Release
_is_debug=false

CFLAGS="-Wno-unknown-warning-option -fPIC"
CXXFLAGS="-Wno-unknown-warning-option -fPIC"

_apply_patch() {
	local args="$1" pname="$(basename $2)"

	if [ ! -f ".${pname}_done" ]; then
		if [ -f "${2}.args" ]; then
			args=$(<"${2}.args")
		fi
		msg_normal "$pkgver: patching: ${pname}.\n"
		patch -N $args -i $2
		touch .${pname}_done
	fi
}

_git_am() {
	local pname="$(basename $1)"

	if [ ! -f ".${pname}_done" ]; then
		msg_normal "$pkgver: patching: ${pname}.\n"
		git -c 'user.name=Electron build' -c 'user.email=electron@ebuild' \
			am --exclude "third_party/blink/tools/**" \
			--exclude "test/mjsunit/**" --exclude "content/test/**" \
			--exclude "test/cctest/**" --exclude "test/unittests/**" \
			--exclude "third_party/blink/web_tests/**" \
			--exclude "chrome/test/**" \
			$1
		touch .${pname}_done
	fi
}


_get_chromium_arch() {
	case "$1" in
		x86_64*) echo x64 ;;
		i686*) echo x86 ;;
		arm*) echo arm ;;
		aarch64*) echo arm64 ;;
		ppc64*) echo ppc64 ;;
		ppc*) echo ppc ;;
		mipsel*) echo mipsel ;;
		mips*) echo mips ;;
		*) msg_error "$pkgver: cannot be compiled for ${XBPS_TARGET_MACHINE}.\n" ;;
	esac
}

post_extract() {
	mv chromium-${_chromiumver} src
	mkdir -p src/third_party/
	mv node-$_nodever src/third_party/electron_node
	mv electron-${version} src/electron
}

_git_init() {
	repopath="$1"
	cd "$wrksrc"/"$repopath"
	git init -q
	git config "gc.auto" 0
	if [ "$repopath" != "src" ]; then
		echo "/${repopath#src/}" >> "$wrksrc/$build_wrksrc/.gitignore"
	fi
	git add .
	git -c 'user.name=Electron build' -c 'user.email=electron@ebuild' \
		commit -q -m "." || true

}

pre_patch() {
	cd $wrksrc
	for x in $FILESDIR/patches/*.patch; do
		case "${x##*/}" in
			electron*.patch)
				cd src/electron
				_apply_patch -p1 "$x"
				cd "$wrksrc";;
		esac
	done

	# Sigh, electron uses git am...
	if [ ! -f ".electron_patches_done" ]; then
	mv src/electron/patches/config.json config.json.old
	jq 'del(."src/electron/patches/Mantle", ."src/electron/patches/ReactiveObjC",
		."src/electron/patches/squirrel.mac", ."src/electron/patches/nan")' \
		config.json.old > src/electron/patches/config.json

	python3.11 src/electron/script/list_patch_targets.py src/electron/patches/config.json | while read -r repopath; do
		_git_init $repopath
	done
	_git_init src/electron
	cd $wrksrc

	for x in $FILESDIR/chromium-upstream-patches/*.patch; do
		[ -f $x ] || continue
		cd src
		_git_am "$x"
		cd "$wrksrc"
	done

	python3.11 src/electron/script/apply_all_patches.py src/electron/patches/config.json
	touch .electron_patches_done
	fi

	for x in $FILESDIR/patches/*; do
		case "${x##*/}" in
			chromium*.patch)
				cd src
				_apply_patch -p1 "$x"
				cd "$wrksrc";;
		esac
	done

	if [ "$XBPS_TARGET_LIBC" = "musl" ]; then
	for x in $FILESDIR/musl-patches/*; do
		case "${x##*/}" in
			chromium*.patch)
				cd src
				_apply_patch -p1 "$x"
				cd "$wrksrc";;
			electron*.patch)
				cd src/electron
				_apply_patch -p1 "$x"
				cd "$wrksrc";;
		esac
	done
	fi
	if [ "$build_option_sndio" ]; then
		mkdir -p ${wrksrc}/${build_wrksrc}/media/audio/{sndio,openbsd}
		cp ${FILESDIR}/sndio-files/sndio_*put.* \
			${wrksrc}/${build_wrksrc}/media/audio/sndio
		cp ${FILESDIR}/sndio-files/audio_manager_openbsd.* \
			${wrksrc}/${build_wrksrc}/media/audio/openbsd
		for f in "${FILESDIR}"/sndio-patches/*.patch; do
			cd src
			_apply_patch -p0 "$f"
			cd "$wrksrc"
		done
	fi
	vsed -i 's/OFFICIAL_BUILD/GOOGLE_CHROME_BUILD/' \
		src/tools/generate_shim_headers/generate_shim_headers.py
}

pre_configure() {
	ln -sf "/usr/bin/python3.11" "${XBPS_WRAPPERDIR}/python3"

	cd "$wrksrc/$build_wrksrc"

	# https://groups.google.com/a/chromium.org/d/topic/chromium-packagers/9JX1N2nf4PU/discussion
	touch chrome/test/data/webui/i18n_process_css_test.html
	# Use the file at run time instead of effectively compiling it in
	sed 's|//third_party/usb_ids/usb.ids|/usr/share/hwdata/usb.ids|g' \
		-i services/device/public/cpp/usb/BUILD.gn

	vsed -e 's|python3.10|python3.11|g' -i third_party/electron_node/configure
	vsed -e "s|(3, 10)|(3, 11)|" -i third_party/electron_node/configure

	mkdir -p third_party/node/linux/node-linux-x64/bin
	ln -sf /usr/bin/node third_party/node/linux/node-linux-x64/bin/
	rm -f third_party/devtools-frontend/src/third_party/esbuild/esbuild

	# compile gn early, so it can be used to generate gni stuff
	msg_normal "Bootstrapping GN\n"
	CC="${CC_FOR_BUILD:-$CC}" CXX="${CXX_FOR_BUILD:-$CXX}" LD="${LD_FOR_BUILD:-$LD}" \
	CFLAGS="${CFLAGS_FOR_BUILD:-$CFLAGS}" \
	CXXFLAGS="${CXXFLAGS_FOR_BUILD:-$CXXFLAGS} -Wno-error=redundant-move" \
	LDFLAGS="${XBPS_LDFLAGS}" \
		python3.11 tools/gn/bootstrap/bootstrap.py -s -v --skip-generate-buildfiles

	# we need to generate ppc64 stuff for libvpx as it's not shipped
	# this has to be done before unbundling, but after gn is built
	# comment out if we switch back to system libvpx again later
	case "$XBPS_TARGET_MACHINE" in
		ppc64*)
			pushd third_party/libvpx
			mkdir -p source/config/linux/ppc64
			# need PATH to find gn
			PATH="${wrksrc}/${build_wrksrc}/out/Release:$PATH" \
				./generate_gni.sh || \
					msg_error "failed to generate libvpx gni"
			popd
			;;
	esac

	# reusable system library settings
	local use_system="
		ffmpeg
		flac
		fontconfig
		freetype
		harfbuzz-ng
		libdrm
		libevent
		libjpeg
		libpng
		libwebp
		libxml
		libxslt
		opus
		re2
		snappy
		"
	for _lib in $use_system libjpeg_turbo; do
		msg_normal "Removing buildscripts for system provided $_lib\n"
		find -type f -path "*third_party/$_lib/*" \
			\! -path "*third_party/$_lib/chromium/*" \
			\! -path "*third_party/$_lib/google/*" \
			\! -path './base/third_party/icu/*' \
			\! -path './third_party/pdfium/third_party/freetype/include/pstables.h' \
			\! -path './third_party/harfbuzz-ng/utils/hb_scoped.h' \
			\! -regex '.*\.\(gn\|gni\|isolate\|py\)' \
			-delete
	done


	msg_normal "Replacing gn files\n"
	python3.11 build/linux/unbundle/replace_gn_files.py \
		--system-libraries $use_system
	third_party/libaddressinput/chromium/tools/update-strings.py

	# Satisfy some scripts that use git describe to figure out the electron version
	cd ${wrksrc}/src/electron
	git tag -f "v${version}"
}

do_configure() {
	local target_arch="$(_get_chromium_arch ${XBPS_TARGET_MACHINE})"
	local host_arch="$(_get_chromium_arch ${XBPS_MACHINE})"
	# the build system will set march for use, adding it to cflags will break builds
	export CXXFLAGS=$( shopt -s extglob; echo ${CXXFLAGS/-march=*([^ ])} )
	export CFLAGS=$( shopt -s extglob; echo ${CFLAGS/-march=*([^ ])} )
	export CFLAGS=${CFLAGS/-g/}
	export CXXFLAGS=${CXXFLAGS/-g/}
	local conf=()
	cd third_party/electron_node
	if [ "$CROSS_BUILD" ]; then
		conf_args=" --dest-cpu=${target_arch} --cross-compiling"
	fi
	./configure --prefix=/usr \
		--shared-zlib \
		--shared-libuv \
		--shared-openssl \
		--shared-cares \
		--openssl-use-def-ca-store \
		--without-npm \
		--without-dtrace \
		--without-bundled-v8 \
		${conf_args}

	cd "$wrksrc/$build_wrksrc"/electron
	yarn install --frozen-lockfile
	cd "$wrksrc/$build_wrksrc"

	if [ "$build_option_clang" ]; then
		export CC=clang
		export CXX=clang++
		export HOST_CC=clang
		export HOST_CXX=clang++
	else
		export CXXFLAGS="$CXXFLAGS -fpermissive"
		export BUILD_CXXFLAGS="$BUILD_CXXFLAGS -fpermissive"
		export BUILD_AR="$AR_host"
		export BUILD_NM="$NM_host"
	fi

	conf+=(
		'import("//electron/build/args/release.gn")'
		'blink_symbol_level=0'
		'clang_use_chrome_plugins=false'
		'custom_toolchain="//build/toolchain/linux/unbundle:default"'
	)
	if [ "$CROSS_BUILD" ]; then
		conf+=(
			'host_toolchain="//build/toolchain/linux/unbundle:host"'
			'v8_snapshot_toolchain="//build/toolchain/linux/unbundle:host"'
			"host_pkg_config=\"$PKG_CONFIG_FOR_BUILD\""
			"pkg_config=\"$PKG_CONFIG\""
		)
	else
		conf+=(
			'host_toolchain="//build/toolchain/linux/unbundle:default"'
			'v8_snapshot_toolchain="//build/toolchain/linux/unbundle:default"'
		)
	fi
	if [ "$build_option_sndio" ]; then
		conf+=(
			'use_sndio=true'
		)
	fi
	if [ -n "$XBPS_DEBUG_PKGS" ]; then
		conf+=('symbol_level=1')
	else
		conf+=('symbol_level=0')
	fi

	# this does not work on ppc64 yet
	case "$XBPS_TARGET_MACHINE" in
		ppc64*) conf+=( "enable_jxl_decoder=false" );;
	esac

	conf+=(
		'devtools_skip_typecheck=false'
		'enable_hangout_services_extension=true'
		'enable_nacl=false'
		'enable_precompiled_headers=false'
		'fatal_linker_warnings=false'
		'ffmpeg_branding="Chrome"'
		'gold_path="/usr/bin/ld.gold"'
		'icu_use_data_file=true'
		"is_clang=$(vopt_if clang true false)"
		'clang_base_path="/usr"'

		'is_component_build=false'
		"is_debug=$_is_debug"
		'proprietary_codecs=true'
		'treat_warnings_as_errors=false'
		'use_cups=true'
		'use_custom_libcxx=false'
		'use_gnome_keyring=false'
		'use_gold=false'
		"use_lld=$(vopt_if clang true false)"

		'is_cfi=false'
		'use_thin_lto=false'
		'use_cfi_icall=false'
		'chrome_pgo_phase=0'

		"use_pulseaudio=$(vopt_if pulseaudio 'true' 'false')"
		"rtc_use_pipewire=$(vopt_if pipewire true false)"
		'use_sysroot=false'
		'use_system_harfbuzz=true'
		'use_system_libffi=true'
		'is_component_ffmpeg=false'
		"target_cpu=\"$target_arch\""
		"host_cpu=\"$host_arch\""
	)

	msg_normal "Configuring build\n"
	out/Release/gn gen out/$_buildtype --args="${conf[*]}"
}

do_build() {
	export CXXFLAGS=$( shopt -s extglob; echo ${CXXFLAGS/-march=*([^ ])} )
	export CFLAGS=$( shopt -s extglob; echo ${CFLAGS/-march=*([^ ])} )
	export CFLAGS=${CFLAGS/-g/}
	export CXXFLAGS=${CXXFLAGS/-g/}
	if [ "$build_option_clang" ]; then
		export CC=clang
		export CXX=clang++
		export HOST_CC=clang
		export HOST_CXX=clang++
	else
		export BUILD_CXXFLAGS="$BUILD_CXXFLAGS -fpermissive"
		export CXXFLAGS="$CXXFLAGS -fpermissive"
		export BUILD_AR="$AR_host"
		export BUILD_NM="$NM_host"
	fi
	msg_normal "Ninja turtles GO!\n"
	ninja ${makejobs} -C out/$_buildtype electron third_party/electron_node:headers
	# finish rest of the build
	strip -s out/$_buildtype/electron
	ninja ${makejobs} -C out/$_buildtype electron_dist_zip
}

do_install() {
	vmkdir /usr/lib/$pkgname
	vmkdir /usr/include/$pkgname
	bsdtar -xf out/$_buildtype/dist.zip -C "$DESTDIR/usr/lib/$pkgname"

	chmod u+s "$DESTDIR/usr/lib/$pkgname/chrome-sandbox"

	cp out/$_buildtype/gen/node_headers.tar.gz "$DESTDIR"/usr/include/$pkgname

	vlicense ${wrksrc}/src/LICENSE chromium.LICENSE
	vlicense ${wrksrc}/src/electron/LICENSE electron.LICENSE
	vlicense ${wrksrc}/src/third_party/electron_node/LICENSE node.LICENSE

	vmkdir /usr/bin
	ln -s ../lib/$pkgname/electron "$DESTDIR"/usr/bin/$pkgname
}
