# Template file for 'electron13'
pkgname=electron13
version=13.3.0
revision=1
_nodever=14.16.0
_chromiumver=91.0.4472.69
archs="x86_64* i686* aarch64* ppc64le*"
create_wrksrc=yes
build_wrksrc="src"
hostmakedepends="$(vopt_if clang clang) python pkgconf perl gperf bison ninja nodejs hwids
 libwebp-devel freetype-devel harfbuzz-devel libpng-devel nss-devel which git libevent-devel
 pciutils-devel libatomic-devel ffmpeg-devel libxml2-devel libglib-devel yarn openjdk 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"
makedepends="libpng-devel gtk+-devel gtk+3-devel nss-devel pciutils-devel
 libXi-devel libgcrypt-devel libgnome-keyring-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 libatomic-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"
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="1707f46439407ed0500e44d61c5171ce00f225d1478349472a0e45920d6a75a1
 1f6843c636f4adee6b06c301193810cce103ee3e4582d4cbc31c915efc3d0c7b
 bcdf869b0743405515ee897b1047b5e851a717e426b4974d26537c9b10dfd53a"

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

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="No proper setup for using clang as cross compiler in void yet"
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
		msg_normal "$pkgver: patching: ${pname}.\n"
		patch -N $args -i $2
		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
}
post_patch() {
	cd $wrksrc
	for x in $FILESDIR/patches/*; 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

	python2 src/electron/script/list_patch_targets.py src/electron/patches/config.json | while read -r repopath; do
		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
	done
	cd $wrksrc
	python2 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 -p0 "$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
}

pre_configure() {
	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

	mkdir -p third_party/node/linux/node-linux-x64/bin
	ln -s /usr/bin/node third_party/node/linux/node-linux-x64/bin/

	# 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}" \
	LDFLAGS="${XBPS_LDFLAGS}" \
		python2 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"
	python2 build/linux/unbundle/replace_gn_files.py --system-libraries \
		$use_system
	third_party/libaddressinput/chromium/tools/update-strings.py
}

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
	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+=(
		'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+=(
		'enable_hangout_services_extension=true'
		'enable_nacl_nonsfi=false'
		'enable_nacl=false'
		'enable_precompiled_headers=false'
		'fatal_linker_warnings=false'
		'ffmpeg_branding="Chrome"'
		'fieldtrial_testing_like_official_build=true'
		'gold_path="/usr/bin/ld.gold"'
		'icu_use_data_file=true'
		"is_clang=$(vopt_if clang true false)"
		'is_component_build=false'
		"is_debug=$_is_debug"
		'proprietary_codecs=true'
		'treat_warnings_as_errors=false'
		'use_allocator_shim=false'
		'use_allocator="none"'
		'use_cups=true'
		'use_custom_libcxx=false'
		'use_gnome_keyring=false'
		'use_gold=false'
		'use_lld=false'
		'use_system_libwayland=true'
		"use_pulseaudio=$(vopt_if pulseaudio 'true' 'false')"
		"rtc_use_pipewire=$(vopt_if pipewire true false)"
		'rtc_pipewire_version="0.3"'
		'use_sysroot=false'
		'use_system_harfbuzz=true'
		"target_cpu=\"$target_arch\""
		"host_cpu=\"$host_arch\""
		'import("//electron/build/args/release.gn")'
	)

	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
}
