# vim: ft=make ts=4 sw=4 noet
.DEFAULT_GOAL := all

NAME    = basilisk
VERSION = euxp
GARTYPE = v2

DESCRIPTION = Basilisk browser (UXP/GTK3) tracking the euxp branch
define BLURB
  Basilisk is a web browser based on the Unified XUL Platform (UXP),
  a fork of Mozilla Firefox 52 ESR. This build tracks the euxp branch.
endef

# Source comes from git (recursive clone for platform/ submodule).
# No DISTFILES — fetch/checksum/extract are no-ops; post-extract does the clone.
DISTFILES =
DISTNAME  = basilisk-mirror-euxp

LICENSE = LICENSE

BUILD_DEP_PKGS += OZSWgit OZSWgcc12 OZSWpkgconf OZSWpy311
BUILD_DEP_PKGS += OZSWgtk3 OZSWcairo OZSWpango OZSWglib
BUILD_DEP_PKGS += OZSWlibX11 OZSWlibXt OZSWlibXext OZSWlibXft OZSWlibXrender OZSWlibXmu
BUILD_DEP_PKGS += OZSWfreetype OZSWfontconfig OZSWlibpng OZSWlibjpeg OZSWzlib

PACKAGES                      += OZSWbasilisk
SPKG_DESC_OZSWbasilisk         = Basilisk browser (UXP, GTK3, euxp branch)
CATALOGNAME_OZSWbasilisk       = basilisk
RUNTIME_DEP_PKGS_OZSWbasilisk += OZSWgcc12rt OZSWzlib
RUNTIME_DEP_PKGS_OZSWbasilisk += OZSWgtk3 OZSWcairo OZSWpango OZSWglib
RUNTIME_DEP_PKGS_OZSWbasilisk += OZSWlibX11 OZSWlibXt OZSWlibXext OZSWlibXft OZSWlibXrender
RUNTIME_DEP_PKGS_OZSWbasilisk += OZSWfreetype OZSWfontconfig OZSWlibpng OZSWlibjpeg

# UXP/mach handles configure and build — skip GAR's defaults
CONFIGURE_SCRIPTS =
BUILD_SCRIPTS     =
INSTALL_SCRIPTS   =

post-extract:
	@echo "==> Cloning Basilisk euxp branch with platform submodule"
	@if [ ! -d $(WORKSRC)/.git ]; then \
		mkdir -p $(WORKDIR); \
		git clone -b euxp --single-branch --recursive --depth=1 \
			https://github.com/Basilisk-Development-Team/basilisk-mirror.git \
			$(WORKSRC); \
	fi
	@echo "==> Creating /opt/ozsw/bin helper symlinks"
	@test -f /opt/ozsw/bin/grep || sudo ln -s /usr/bin/ggrep /opt/ozsw/bin/grep
	@test -f /opt/ozsw/bin/pkg-config || sudo ln -s /opt/ozsw/bin/pkgconf /opt/ozsw/bin/pkg-config
	@test -f /opt/ozsw/bin/python || sudo ln -s /opt/ozsw/bin/python3 /opt/ozsw/bin/python
	@echo "==> Patching for Python 3 and Solaris"
	@gsed -i "s/error = e\.message/error = str(e)/" \
		$(WORKSRC)/platform/build/moz.configure/checks.configure
	@printf '#!/bin/sh\nexec /opt/ozsw/bin/python3 "$$(dirname "$$0")/platform/mach" "$$@"\n' \
		> $(WORKSRC)/mach
	@chmod +x $(WORKSRC)/mach
	@/opt/ozsw/bin/python3 /opt/ozsw/lib/ozsw-patch-mach.py $(WORKSRC)/platform/mach
	@gsed -i 's|PYTHON ?= $$(shell which python3 > /dev/null 2>&1 && echo python3 || echo python)|PYTHON ?= /opt/ozsw/bin/python3|' \
		$(WORKSRC)/client.mk
	@# Fix mozconfig.py IGNORE_SHELL_VARIABLES: bash internal arrays (BASH_ARGC etc.)
	@# pollute old-configure.vars via 'set' output after .mozconfig functions run
	@gsed -i "s/    IGNORE_SHELL_VARIABLES = {'_'}/    IGNORE_SHELL_VARIABLES = {'_', 'BASH_ARGC', 'BASH_ARGV', 'BASH_LINENO', 'BASH_SOURCE', 'BASH_VERSINFO', 'DIRSTACK', 'FUNCNAME', 'GROUPS', 'PIPESTATUS', 'BASH_REMATCH', '_mozconfig_opt', '_mozconfig_name', '_mozconfig_op', '_mozconfig_app', 'opt'}/" \
		$(WORKSRC)/platform/python/mozbuild/mozbuild/mozconfig.py
	@# Fix platform/old-configure: fallback PYTHON if old-configure.vars sourcing aborted
	@gsed -i '12a # OZSW: ensure PYTHON is set even if old-configure.vars sourcing aborted early\n: $${PYTHON:=/opt/ozsw/bin/python3}' \
		$(WORKSRC)/platform/old-configure
	@# Fix NSPR moz.build for SunOS: missing OS_LIBS (-lnsl -lsocket -lrt -ldl).
	@# Also replace _PR_HAVE_OFF64_T with _PR_NO_LARGE_FILES: the former makes unix.c
	@# take a direct reference to open64@SUNW_1.1 which GNU ld on OpenSolaris
	@# mishandles, producing "invalid version 15 (max 0)" link errors.
	@/opt/ozsw/bin/python3 -c "\
path='$(WORKSRC)/platform/config/external/nspr/pr/moz.build'; \
c=open(path).read(); \
c=c.replace(\"        _PR_HAVE_OFF64_T=True,\", \"        _PR_NO_LARGE_FILES=True,  # open64@SUNW_1.1 confuses GNU ld\"); \
c=c.replace(\"    DEFINES['SOLARIS'] = True\", \"    DEFINES['SOLARIS'] = True\n    OS_LIBS += ['-lpthread', '-lsocket', '-lnsl', '-lrt', '-ldl', '-lc']\"); \
open(path,'w').write(c)"
	@# Fix search moz.build: basilisk overrides all platform search components
	@printf '# OZSW: all search components overridden by basilisk/components/search/service/\n' \
		> $(WORKSRC)/platform/toolkit/components/search/moz.build
	@# Fix Chromium IPC: pthread_setname_np not available on OpenSolaris 2009 (snv_111b)
	@/opt/ozsw/bin/python3 -c "\
path='$(WORKSRC)/platform/ipc/chromium/src/base/platform_thread_posix.cc'; \
c=open(path).read(); \
old='#elif defined(OS_SOLARIS)\n  pthread_setname_np(pthread_self(), name);'; \
new='#elif defined(OS_SOLARIS)\n  /* pthread_setname_np not available on OpenSolaris 2009 */'; \
open(path,'w').write(c.replace(old,new))"
	@# Fix Skia GrAutoLocaleSetter.h: uselocale/freelocale/newlocale/locale_t not on
	@# OpenSolaris 2009 (snv_111b). Disable HAVE_LOCALE_T for __sun the same way it
	@# is disabled for Android/uclibc/newlib.
	@gsed -i 's/#if defined(SK_BUILD_FOR_ANDROID) || defined(__UCLIBC__) || defined(_NEWLIB_VERSION)/#if defined(SK_BUILD_FOR_ANDROID) || defined(__UCLIBC__) || defined(_NEWLIB_VERSION) || defined(__sun)/' \
		$(WORKSRC)/platform/gfx/skia/skia/src/gpu/GrAutoLocaleSetter.h
	@# Fix libjxl color_encoding_internal.h: Solaris sys/regset.h (pulled in via
	@# <sys/ucontext.h> when __EXTENSIONS__ is set) defines CS=15, conflicting with
	@# the local 'using CS = ColorSpace' alias. Undef it just before the alias.
	@/opt/ozsw/bin/python3 -c "\
path='$(WORKSRC)/platform/media/libjxl/src/lib/jxl/color_encoding_internal.h'; \
c=open(path).read(); \
old='  using CS = ColorSpace;'; \
new='#ifdef CS\n#undef CS  /* Solaris sys/regset.h defines CS=15 */\n#endif\n  using CS = ColorSpace;'; \
open(path,'w').write(c.replace(old,new))"
	@# Fix js/src/threading/posix/Thread.cpp: pthread_setname_np absent on OpenSolaris snv_111b.
	@# Add __sun no-op before the #else branch that calls it unconditionally.
	@gsed -i 's/#elif defined(__NetBSD__)$$/#elif defined(__sun)\\n  \/* pthread_setname_np absent on OpenSolaris snv_111b *\/\\n#elif defined(__NetBSD__)/' \\
		$(WORKSRC)/platform/js/src/threading/posix/Thread.cpp
	@# Fix libevent bundled Solaris event-config.h: arc4random incorrectly marked available.
	@gsed -i 's/^#define _EVENT_HAVE_ARC4RANDOM 1$$/\/\* #undef _EVENT_HAVE_ARC4RANDOM *\/ \/\* absent on OpenSolaris snv_111b *\//' \\
		$(WORKSRC)/platform/ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h
	@gsed -i 's/^#define _EVENT_HAVE_ARC4RANDOM_BUF 1$$/\/\* #undef _EVENT_HAVE_ARC4RANDOM_BUF *\/ \/\* absent on OpenSolaris snv_111b *\//' \\
		$(WORKSRC)/platform/ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h
	@# Fix arc4random.c: removes XP_SOLARIS block that includes Chromium-specific
	@# build/build_config.h (not in include path when compiled as static include of evutil_rand.c)
	@gsed -i '/#ifdef XP_SOLARIS/,/#endif/d' \
		$(WORKSRC)/platform/ipc/chromium/src/third_party/libevent/arc4random.c
	@# Fix libopus silk/resampler_private.h: Solaris sys/regset.h also defines SS=18
	@# (x86 stack-segment register index), conflicting with the 'SS' parameter name.
	@/opt/ozsw/bin/python3 -c "\
path='$(WORKSRC)/platform/media/libopus/silk/resampler_private.h'; \
c=open(path).read(); \
old='#ifndef SILK_RESAMPLER_PRIVATE_H\n#define SILK_RESAMPLER_PRIVATE_H'; \
new='#ifndef SILK_RESAMPLER_PRIVATE_H\n#define SILK_RESAMPLER_PRIVATE_H\n/* Solaris sys/regset.h defines SS=18 (x86 stack segment register index) */\n#ifdef SS\n#undef SS\n#endif'; \
open(path,'w').write(c.replace(old,new))"
	@# Fix libpng moz.build: -std=c89 + _XOPEN_SOURCE=600 is rejected by Solaris
	@# feature_tests.h (XPG6/UNIX 03 requires C99). Use gnu99 on SunOS instead.
	@gsed -i "s/    CFLAGS += \['-std=c89'\]/    if CONFIG['OS_TARGET'] == 'SunOS':\n        CFLAGS += ['-std=gnu99']  # c89 + _XOPEN_SOURCE=600 rejected by Solaris feature_tests.h\n    else:\n        CFLAGS += ['-std=c89']/" \
		$(WORKSRC)/platform/media/libpng/moz.build
	@# Fix toolkit/library/libxul.mk: NSModules ordering check fails on Solaris because
	@# GNU ld places sentinel symbols differently than Linux. The runtime ordering IS
	@# correct per Mozilla bug reports; the check just has wrong expectations. Disable it.
	@gsed -i 's/^LOCAL_CHECKS = test .*/# LOCAL_CHECKS disabled: Solaris GNU ld ordering OK at runtime/' \
		$(WORKSRC)/platform/toolkit/library/libxul.mk
	@gsed -i '/^# LOCAL_CHECKS disabled:/a LOCAL_CHECKS = $$(true)' \
		$(WORKSRC)/platform/toolkit/library/libxul.mk
	@gsed -i 's/^LOCAL_CHECKS += ; test .*/# &/' \
		$(WORKSRC)/platform/toolkit/library/libxul.mk
	@# Fix xpcom nsMemoryReporterManager.cpp: _XOPEN_SOURCE>=500 (set globally) causes
	@# Solaris to enable large file mode (_FILE_OFFSET_BITS=64), but procfs.h
	@# explicitly rejects that. Undef the large-file macros before the procfs include.
	@/opt/ozsw/bin/python3 -c "\
path='$(WORKSRC)/platform/xpcom/base/nsMemoryReporterManager.cpp'; \
c=open(path).read(); \
old='#elif defined(XP_SOLARIS)\n\n#include <procfs.h>'; \
new='#elif defined(XP_SOLARIS)\n\n/* Solaris procfs.h rejects _FILE_OFFSET_BITS=64 (set by _XOPEN_SOURCE>=500) */\n#ifdef _FILE_OFFSET_BITS\n#undef _FILE_OFFSET_BITS\n#endif\n#ifdef _LARGEFILE_SOURCE\n#undef _LARGEFILE_SOURCE\n#endif\n#include <procfs.h>'; \
open(path,'w').write(c.replace(old,new))"
	@echo "==> Writing .mozconfig"
	@{ \
		echo '# Basilisk euxp build for OpenSolaris i386 (snv_111b)'; \
		echo 'ac_add_options --enable-application=basilisk'; \
		echo 'ac_add_options --enable-optimize="-O2 -w"'; \
		echo 'ac_add_options --disable-official-branding'; \
		echo 'ac_add_options --enable-default-toolkit=cairo-gtk3'; \
		echo 'ac_add_options --enable-jemalloc'; \
		echo 'ac_add_options --enable-strip'; \
		echo 'ac_add_options --enable-devtools'; \
		echo 'ac_add_options --enable-av1'; \
		echo 'ac_add_options --disable-pie'; \
		echo 'ac_add_options --disable-webrtc'; \
		echo 'ac_add_options --disable-gamepad'; \
		echo 'ac_add_options --disable-tests'; \
		echo 'ac_add_options --disable-debug'; \
		echo 'ac_add_options --disable-necko-wifi'; \
		echo 'ac_add_options --disable-updater'; \
		echo 'ac_add_options --disable-npapi'; \
		echo 'ac_add_options --disable-dbus'; \
		echo 'ac_add_options --disable-pulseaudio'; \
		echo 'ac_add_options --with-pthreads'; \
		echo 'ac_add_options --prefix=$(prefix)'; \
		echo '# Force 32-bit build: OZSW GCC12 target is i386-pc-solaris2.11'; \
		echo 'ac_add_options --host=i386-pc-solaris2.11'; \
		echo 'ac_add_options --target=i386-pc-solaris2.11'; \
		echo 'export CC=/opt/ozsw/bin/gcc'; \
		echo 'export CXX=/opt/ozsw/bin/g++'; \
		echo 'export HOST_CC=/opt/ozsw/bin/gcc'; \
		echo 'export HOST_CXX=/opt/ozsw/bin/g++'; \
		echo ''; \
		echo 'export BASILISK_VERSION=1'; \
		echo 'export MOZ_PKG_SPECIAL=gtk3'; \
		echo 'export CONFIG_SHELL=/usr/bin/bash'; \
		echo 'mk_add_options MOZ_MAKE_FLAGS="-j3"'; \
		echo 'mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/obj-build'; \
		echo 'export MOZILLA_OFFICIAL=1'; \
		echo ''; \
		echo 'ac_add_options --x-libraries=$(BUILD_PREFIX)/lib'; \
		echo 'export PKG_CONFIG_PATH=$(BUILD_PREFIX)/lib/pkgconfig:$(BUILD_PREFIX)/share/pkgconfig'; \
		echo ''; \
		echo '# Solaris: _POSIX_C_SOURCE=200809L (from zbuild.h) not handled by old'; \
		echo '# feature_tests.h; _XOPEN_SOURCE=600 gets _XPG6 so C99 + POSIX is valid.'; \
		echo '# __EXTENSIONS__ exposes Solaris-specific APIs (madvise, MADV_DONTNEED etc.)'; \
		echo 'export CFLAGS="-D_XOPEN_SOURCE=600 -D__EXTENSIONS__"'; \
		echo 'export CXXFLAGS="-D_XOPEN_SOURCE=600 -D__EXTENSIONS__"'; \
	} > $(WORKSRC)/.mozconfig
	@$(MAKECOOKIE)

pre-build:
	@echo "==> Configuring Basilisk with mach"
	cd $(WORKSRC) && \
		PATH="/opt/ozsw/bin:/opt/oz/bin:/usr/bin:/bin:/usr/sfw/bin:/usr/ccs/bin" \
		MOZCONFIG=$(WORKSRC)/.mozconfig \
		/opt/ozsw/bin/python3 ./platform/mach configure
	@echo "==> Setting up ld wrapper and patching system_wrappers/sys/regset.h"
	@# GNU ld 2.45 on Solaris records SUNW_x.y versioned symbol refs in .so files,
	@# then fails to parse them when linking the next .so ("invalid version N, max 0").
	@# Workaround: wrap ld to strip .gnu.version* sections from .so outputs.
	@# Stripping is safe because ld.so.1 uses SHT_SUNW_versym (not SHT_GNU_versym).
	@# Install ld wrapper at /opt/ozsw/bin/ld (original backed up as ld.real).
	@# -B/tmp/mozld-wrap does NOT work: GCC12 collect2 path is hardcoded at compile time.
	@if [ ! -f /opt/ozsw/bin/ld.real ]; then \
		sudo cp /opt/ozsw/bin/ld /opt/ozsw/bin/ld.real && \
		printf '#!/bin/bash\noutput=""\nnext_o=0\nfor arg in "$$@"; do\n  if [ $$next_o -eq 1 ]; then output="$$arg"; next_o=0; fi\n  if [ "$$arg" = "-o" ]; then next_o=1; fi\ndone\n/opt/ozsw/bin/ld.real "$$@"\nrc=$$?\nif [ $$rc -eq 0 ] && [ -n "$$output" ]; then\n  case "$$output" in\n    *.so|*.so.*) /opt/ozsw/bin/objcopy --remove-section=.gnu.version --remove-section=.gnu.version_r --remove-section=.gnu.version_d "$$output" 2>/dev/null || true ;;\n  esac\nfi\nexit $$rc\n' | sudo tee /opt/ozsw/bin/ld > /dev/null && \
		sudo chmod +x /opt/ozsw/bin/ld; \
	fi
	@echo "==> Patching system_wrappers/sys/regset.h (configure generates this)"
	@# Solaris sys/regset.h defines short x86 register names (CS=15, SS=18, DS=16,
	@# ES=17, FS=20, GS=19, EAX=11, ...) as integer macros. These collide with
	@# variable and parameter names throughout Mozilla/NSS/media code. The system
	@# wrapper is the right place to undef them after the real header is included.
	@printf '#pragma GCC system_header\n#pragma GCC visibility push(default)\n#include_next <sys/regset.h>\n#pragma GCC visibility pop\n/* Undef Solaris i386 register-index macros that conflict with C identifiers */\n#undef SS\n#undef CS\n#undef DS\n#undef ES\n#undef FS\n#undef GS\n#undef EAX\n#undef ECX\n#undef EDX\n#undef EBX\n#undef ESP\n#undef EBP\n#undef ESI\n#undef EDI\n#undef EIP\n#undef EFL\n#undef ERR\n#undef TRAPNO\n#undef UESP\n' \
		> $(WORKSRC)/obj-build/dist/system_wrappers/sys/regset.h
	@echo "==> Patching system_wrappers/sys/ucontext.h: undef CS/SS etc. from Solaris regset.h"
	@printf '#pragma GCC system_header\n#pragma GCC visibility push(default)\n#include_next <sys/ucontext.h>\n#pragma GCC visibility pop\n/* Solaris sys/ucontext.h -> regset.h defines CS=15 etc.; undef to avoid C++ collisions */\n#undef CS\n' \\
		> $(WORKSRC)/obj-build/dist/system_wrappers/sys/ucontext.h
	@echo "==> Adding atk-bridge-2.0 to MOZ_GTK3_LIBS in config.status and autoconf.mk"
	@# config.status stores MOZ_GTK3_LIBS as a Python list; patch '-lgdk-3' entry
	@/opt/ozsw/bin/python3 -c "path='$(WORKSRC)/obj-build/config.status'; c=open(path).read(); \
	old=\"        '-lgdk-3',\\n\"; \
	new=\"        '-lgdk-3',\\n        '-latk-bridge-2.0',\\n\"; \
	open(path,'w').write(c.replace(old,new)) if '-latk-bridge-2.0' not in c else None"
	@gsed -i "s/MOZ_GTK3_LIBS = -lgtk-3 -lgdk-3 /MOZ_GTK3_LIBS = -lgtk-3 -lgdk-3 -latk-bridge-2.0 /" \\
		$(WORKSRC)/obj-build/config/autoconf.mk
	@# Make autoconf.mk newer than config.status to prevent make from regenerating it
	@touch $(WORKSRC)/obj-build/config/autoconf.mk
	@echo "==> Adding -rpath-link dist/bin to OS_LDFLAGS (enables GNU ld to find transitive NSS/sqlite"
	@echo "    deps via libxul.so DT_NEEDED when linking executables like xpcshell)"
	@gsed -i "s|OS_LDFLAGS = |OS_LDFLAGS = -Wl,-rpath-link,$(WORKSRC)/obj-build/dist/bin |" \
		$(WORKSRC)/obj-build/config/autoconf.mk
	@/opt/ozsw/bin/python3 -c "path='$(WORKSRC)/obj-build/config.status'; \
	c=open(path).read(); \
	old=\"    'OS_LDFLAGS': '-lpthread \"; \
	new=\"    'OS_LDFLAGS': '-Wl,-rpath-link,$(WORKSRC)/obj-build/dist/bin -lpthread \"; \
	open(path,'w').write(c.replace(old,new,1)) if '-rpath-link' not in c else None"
	@touch $(WORKSRC)/obj-build/config/autoconf.mk
	@echo "==> Building Basilisk with mach (this will take a long time)"
	cd $(WORKSRC) && \
		PATH="/opt/ozsw/bin:/opt/oz/bin:/usr/bin:/bin:/usr/sfw/bin:/usr/ccs/bin" \
		MOZCONFIG=$(WORKSRC)/.mozconfig \
		/opt/ozsw/bin/python3 ./platform/mach build
	@echo "==> Running mach package (requires LD_LIBRARY_PATH for xpcshell GTK deps)"
	@# Patch package-manifest.in for euxp flat layout (no browser/ prefix for devtools,
	@# no content_geckomediaplugins.xpt which is not built in euxp)
	@gsed -i 's|^@RESPATH@/components/content_geckomediaplugins\.xpt$$|# euxp: GMP not built -- @RESPATH@/components/content_geckomediaplugins.xpt|' \
		$(WORKSRC)/basilisk/installer/package-manifest.in
	@gsed -i 's|@RESPATH@/browser/components/devtools-startup\.|@RESPATH@/components/devtools-startup.|g' \
		$(WORKSRC)/basilisk/installer/package-manifest.in
	@gsed -i 's|@RESPATH@/browser/chrome/devtools|@RESPATH@/chrome/devtools|g' \
		$(WORKSRC)/basilisk/installer/package-manifest.in
	@gsed -i 's|@RESPATH@/browser/@PREF_DIR@/devtools\.js|@RESPATH@/defaults/pref/devtools.js|' \
		$(WORKSRC)/basilisk/installer/package-manifest.in
	cd $(WORKSRC) && \
		PATH="/opt/ozsw/bin:/opt/oz/bin:/usr/bin:/bin:/usr/sfw/bin:/usr/ccs/bin" \
		LD_LIBRARY_PATH="/opt/ozsw/lib" \
		MOZCONFIG=$(WORKSRC)/.mozconfig \
		bash ./mach package
	@$(MAKECOOKIE)

pre-install:
	@echo "==> Installing Basilisk from mach package tarball"
	mkdir -p $(DESTDIR)$(libdir)/basilisk
	mkdir -p $(DESTDIR)$(bindir)
	gtar -xf $(WORKSRC)/obj-build/dist/Basilisk-*.tar.xz \
		-C $(DESTDIR)$(libdir)/basilisk --strip-components=1
	chmod 755 $(DESTDIR)$(libdir)/basilisk/Basilisk
	chmod 755 $(DESTDIR)$(libdir)/basilisk/Basilisk-bin
	@printf '#!/bin/sh\nexec $(libdir)/basilisk/Basilisk "$$@"\n' \
		> $(DESTDIR)$(bindir)/basilisk
	chmod 755 $(DESTDIR)$(bindir)/basilisk
	@$(MAKECOOKIE)

include gar/category.mk
