#!/bin/sh
# ports/firefox/ffstart — the Exec= entry of Firefox.aop (installed into the
# bundle as Contents/AOS/ffstart via APKG_EXEC, see deploy.sh).
#
# WHY THE BUNDLE CARRIES ITS OWN LAUNCHER. The dock, Launchpad and `aoprun`
# start a bundle with NO environment beyond aoprun's LD_LIBRARY_PATH. Firefox
# on this OS is NATIVE-ONLY (owner rule, 2026-08-20: no X11), and the native
# path needs GDK_BACKEND=fasadas — patch 0017's startup gate is explicitly
# narrow and fires ONLY when that variable names the fasadas backend, so a
# bundle whose Exec is the raw binary refuses to start from the dock with
# "Error: no DISPLAY environment variable specified". /bin/ffrun used to be
# the only place these exports lived, which made the dock icon a dead
# double-click; a launcher inside the bundle serves every entry point.
#
# Software WebRender is seeded as a pref rather than hoped for: the fasadas
# PRESENT path has no GL surface (CPU scanout of a memfd), and a pref the
# profile carries is a statement while an absent GL is an accident (same
# reasoning as ffrun's).
#
# WebGL, on the other hand, IS hardware here (Dell, 2026-09-06): it is an
# offscreen FBO on Gecko's own EGL context, composited by software WebRender.
# Measured with an eglGetDisplay(EGL_DEFAULT_DISPLAY) probe in the shipped
# libEGL: Mesa's surfaceless native platform binds /dev/dri/renderD128 and
# GL_RENDERER is "Mesa Intel(R) HD Graphics 4400 (HSW GT2)" — no Gecko source
# change is needed for the display. Two things stood between Firefox and that
# display, and both are environment/prefs, set below:
#   1. Gecko routes WebGL through GLContextProvider::CreateHeadless, which on
#      Linux picks EGL only when gfxVars::UseEGL() — and that is true only on
#      Wayland or with Feature::X11_EGL, which InitX11EGLConfig force-disables
#      unless the glxtest child reported an EGL test type. glxtest's X11 arm does
#      XOpenDisplay and cannot succeed on a fasadas display, so UseEGL() was
#      false, the non-EGL arm is GLX (compiled out), and WebGL failed with an
#      EMPTY reason ("tryNativeGL ()", run 1). MOZ_WEBGL_FORCE_EGL
#      (dom/canvas/WebGLContext.cpp) routes straight to the EGL provider.
#      CORRECTION (patches/0028): this paragraph used to say glxtest "cannot
#      succeed on a fasadas display", full stop. That was true of the X11 ARM
#      only, and it read as a permanent property of glxtest — which is why
#      hardware WebRender looked blocked for longer than it was. glxtest now has
#      a third arm, `fasadas_egltest()`, which needs no display server at all:
#      it hands EGL_DEFAULT_DISPLAY to the same get_egl_status() the Wayland arm
#      uses, so GetTestType() reports EGL and Feature::X11_EGL is no longer
#      force-disabled. MOZ_WEBGL_FORCE_EGL below is now belt-and-braces for
#      WebGL rather than the only route.
#   2. The same failed glxtest blocks FEATURE_WEBGL_USE_HARDWARE by default, so
#      GLLibraryEGL took its SOFTWARE EGL-device arm and rendered on softpipe
#      (run 2, kernel saw no EXECBUFFER2). The per-feature blocklist pref below
#      is the release-build override (gfx.blocklist.all is compiled out on
#      RELEASE_OR_BETA and did nothing, measured).
# With both: GL_RENDERER "Intel(R) HD Graphics" reported to the page and the
# kernel's "i915exec: first EXECBUFFER2 dispatched on RCS" line fired 19 s after
# launch, attributable to Firefox (no other GPU client; a sibling Firefox with
# the old profile had run 18 min without it). Hardware WebRender / VA-API
# remain #646 / #429: the present path, not GL, is what blocks them.
set -u

HERE=$(cd "$(dirname "$0")" && pwd)

export GDK_BACKEND="${GDK_BACKEND:-fasadas}"
export FASADAS_SOCKET="${FASADAS_SOCKET:-/run/fasadas-0}"
export MOZ_CRASHREPORTER_DISABLE=1
[ -n "${FONTCONFIG_FILE:-}" ] || export FONTCONFIG_FILE=/etc/fonts/fonts.conf
export HOME="${HOME:-/root}"

# Where Mesa finds crocus_dri.so — the same two locations agrun names and for
# the same reason (release package vs tree-build squashfs). Measured 2026-09-06
# on the Dell's release install: the loader found crocus WITHOUT this variable
# (the /usr/lib/dri symlinks), so it is belt-and-braces there; agrun measured it
# load-bearing on a tree build, and one launcher must be right for both images.
DRI="/Apps/mesa-egl/Current/lib/dri:/lib/dri:/usr/lib/dri"
export LIBGL_DRIVERS_PATH="${LIBGL_DRIVERS_PATH:+$LIBGL_DRIVERS_PATH:}$DRI"
# See the header: gfxVars::UseEGL() is false on a fasadas display, and the
# alternative arm is GLX, which this build does not have.
export MOZ_WEBGL_FORCE_EGL=1

# ---------------------------------------------------------------------------
# `--no-remote` IS GONE, AND ITS REMOVAL IS THE FIX FOR "FIREFOX DOES NOT LOAD
# THE PAGE YOU ASKED FOR" (2026-09-06)
# ---------------------------------------------------------------------------
# Both exec lines below used to pass `--no-remote`. Firefox 153 does not have
# that flag any more -- toolkit/xre/nsAppRunner.cpp:4739 says so in its own
# words, "Strip the now unsupported no-remote command line argument", and does
# it with `CheckArg("no-remote")`.
#
# ONE of them is therefore harmless. TWO are not, and the chain produced two:
# /bin/ffrun's older form passes `--no-remote` itself, this script saw its
# `--profile` and took the want_profile=0 branch, which added a SECOND one --
#
#     firefox --no-remote --no-remote --profile P <URL>
#
# -- and `CheckArg` BREAKS ON THE FIRST MATCH (toolkit/xre/CmdLineAndEnvUtils.h:
# `if (!aParam) { ar = ARG_FOUND; break; }`), so exactly one is stripped and the
# survivor reaches nsICommandLine. There,
# browser/components/BrowserContentHandler.sys.mjs:1678 does:
#
#     if (curarg.match(/^-/)) {
#       console.error("Warning: unrecognized command line flag", curarg);
#       // To emulate the pre-nsICommandLine behavior, we ignore
#       // the argument after an unrecognized flag.
#       ++i;
#     }
#
# The argument after the surviving `--no-remote` IS THE URL. It is skipped, the
# urilist is empty, and Firefox opens its New Tab -- which reads, exactly, as
# "Firefox does not load pages any more".
#
#   measured: 2026-09-06 on the Dell, two arms, same binary, same page, same
#             aoprun environment, differing ONLY in the flag:
#     A  firefox --profile P file:///...aud2.html
#          -> "AUD2#1 SCRIPT-RAN" in 30 s.                 THE PAGE LOADS.
#     B  firefox --no-remote --no-remote --profile P file:///...aud2.html
#          -> no AUD2# line in 100 s, and the log carries
#             console.error: "Warning: unrecognized command line flag"
#             "-no-remote".                                THE PAGE DOES NOT.
#   by:   the two arms above, launched with aoprun's LD_LIBRARY_PATH
#         (without it Firefox cannot even load XPCOM, which invalidated a first
#         attempt at this measurement and is worth knowing)
#   and:  strace -f -e execve of /bin/ffrun <URL> proves the URL is forwarded
#         INTACT through ffrun -> aoprun -> ffstart -> firefox, so no launcher
#         drops it; the browser discards it on arrival.
#
# Dropping it here fixes the chain even with the OLD /bin/ffrun still deployed:
# one `--no-remote` is stripped by nsAppRunner and nothing survives to eat the
# URL. If a separate instance is ever genuinely wanted, the supported spelling
# is the environment variable MOZ_NO_REMOTE=1, not a flag Gecko has deleted.
#
# The behaviour this gives up is real and is the right trade: a second launch
# now hands its URL to the running browser instead of starting a rival copy,
# which is what a desktop wants and is the only way "open this link" can work.

# Honour a caller that already picked a profile (ffrun's older form passed
# --profile itself; two --profile arguments would make the LAST one win
# silently, which is the kind of ambiguity worth refusing to create).
want_profile=1
for a in "$@"; do
    case "$a" in --profile|--profile=*|-P|-profile) want_profile=0 ;; esac
done
# ---------------------------------------------------------------------------
# PROFILE SEEDING -- IDEMPOTENT, BECAUSE A PREF FIX HAS TO REACH AN EXISTING
# PROFILE
# ---------------------------------------------------------------------------
# Until 2026-09-06 the block below was written only when the profile had no
# user.js:
#
#     if [ ! -f "$PROFILE/user.js" ]; then cat > "$PROFILE/user.js" <<'PREFS'
#
# so a profile written by an OLDER ffstart NEVER gained a pref added later. On
# the Dell that is not hypothetical -- since the HDD install the root is
# persistent ext4, $HOME/.mozilla/ffprofile survives every reboot and every
# `apkg upgrade`, and nothing in the package pipeline touches a profile. A pref
# fix shipped in a new Firefox package therefore reached NOBODY who had already
# started the browser once.
#
#   measured: 2026-09-06, this script run against a profile written by an older
#             copy of itself (a stub `firefox` beside it, so the exec is inert)
#   by:       HOME=<tmp> FFRUN_PROFILE=<tmp>/prof sh ffstart
#     BEFORE 5 distinct prefs, AFTER 9; a fresh profile gets 12
#     still missing after the run:
#         dom.ipc.processHangMonitor      #601 content SIGKILLed mid-decode
#         media.audioipc.shm_area_size    #605 AudioIPC SIGKILL storm
#         security.sandbox.content.level  #580 every remote page renders WHITE
#
# TWO OF THOSE THREE ARE THE FIXES FOR PROCESS-KILL STORMS, which is the
# owner's own report of what dmesg shows.
#
# The WebGL block already had the right shape (a marker line plus an append),
# added by someone who hit exactly this on the existing-profile path and fixed
# only the block in front of them. Generalising it is the repair: every block
# goes through seed_block, so a block added later is idempotent by construction
# and not by whoever writes it remembering.
seed_block() {                     # seed_block <marker>   (block on stdin)
    _m=$1
    if grep -q "$_m" "$PROFILE/user.js" 2>/dev/null; then
        cat > /dev/null            # drain the here-doc rather than leave it
        return 1
    fi
    cat >> "$PROFILE/user.js"
    echo "ffstart: seeded pref block $_m into $PROFILE/user.js" >&2
    return 0
}

# A pref whose VALUE is chosen at LAUNCH cannot use a plain marker: the marker
# would be present after the first launch and the value frozen at whatever that
# launch happened to pick. FF_HW_WEBRENDER=1 on an existing profile would then
# do NOTHING, silently, which is the same defect in a new place.
#
# So this one CONVERGES instead of seeding: it appends only when the EFFECTIVE
# (last) value in user.js is not the wanted one, which is correct in both
# directions -- true->false and false->true.
set_pref_last() {                  # set_pref_last <pref> <value> <comment>
    _p=$1; _v=$2; _w=$3
    _cur=$(sed -n "s/^user_pref(\"$_p\", *\(.*\));.*/\1/p" \
                  "$PROFILE/user.js" 2>/dev/null | tail -1)
    [ "$_cur" = "$_v" ] && return 1
    { echo "// $_w"; echo "user_pref(\"$_p\", $_v);"; } >> "$PROFILE/user.js"
    echo "ffstart: $_p = $_v (was ${_cur:-unset})" >&2
    return 0
}

if [ "$want_profile" = 1 ]; then
    PROFILE="${FFRUN_PROFILE:-$HOME/.mozilla/ffprofile}"
    # A profile that cannot be written is a browser that starts with NONE of
    # the prefs below -- white pages (#580) and process-kill storms (#601,
    # #605) -- and `set -u` alone would not have said a word about it.
    # mkdir -p IS NOT AVAILABLE ON THIS SYSTEM. The busybox in the shipped
    # image rejects -p outright ("mkdir: unrecognized option: p" — its mkdir
    # applet is built with CONFIG_LONG_OPTS off and the option never reaches
    # the short-option parser), so this line failed even when the directory
    # ALREADY EXISTED: ffstart exited 1 and Firefox never launched at all.
    # Measured on the Dell 2026-09-08; plain `mkdir` works, `mkdir -p` does not.
    # Create the parents by hand instead. The check that matters is whether the
    # directory is there afterwards, not which call made it.
    if [ ! -d "$PROFILE" ]; then
        _ffd=""
        _ffifs=$IFS; IFS=/
        for _ffc in $PROFILE; do
            IFS=$_ffifs
            [ -n "$_ffc" ] || continue
            _ffd="$_ffd/$_ffc"
            [ -d "$_ffd" ] || mkdir "$_ffd" 2>/dev/null || true
            IFS=/
        done
        IFS=$_ffifs
    fi
    [ -d "$PROFILE" ] || {
        echo "ffstart: cannot create the profile directory $PROFILE" >&2; exit 1; }
    : >> "$PROFILE/user.js" || {
        echo "ffstart: cannot write $PROFILE/user.js" >&2; exit 1; }

    # The WebRender backend line is written OUTSIDE a quoted heredoc on
    # purpose. Two reasons, both found by trying the other way: unquoting the
    # heredoc to interpolate a variable would also make the BACKTICKS in the
    # core block (the `gfx.webrender.max-partial-present-rects` comment) into
    # command substitution and destroy that text; and the obvious one-liner
    # ${FF_HW_WEBRENDER:+false}${FF_HW_WEBRENDER:-true} expands to "false1"
    # when the variable is set to 1, because :- yields the VALUE, not the
    # default. Measured, both of them.
    #
    # Software by DEFAULT, still. patches/0028 + 0029 add a real hardware arm
    # (glxtest can now report TEST_TYPE=EGL on a fasadas display, and
    # RenderCompositorFasadas renders WebRender into a GPU FBO and reads it
    # back into the widget surface), but it is OPT-IN and stays that way until
    # it has been proven on hardware. #646 step 3 is explicit: never flip it
    # unconditionally, because a machine without /dev/dri/card0 -- QEMU, any
    # non-Intel box -- must keep today's proven software WebRender exactly.
    if [ "${FF_HW_WEBRENDER:-0}" = 1 ]; then
        wr_software=false
    else
        wr_software=true
    fi
    set_pref_last gfx.webrender.software "$wr_software" \
        "ffstart: WebRender backend, FF_HW_WEBRENDER=${FF_HW_WEBRENDER:-0}. Set it
// to 1 to try the GPU path; safe to try anywhere (RenderCompositorFasadas::Create
// returns null with no SingletonGL or on a software rasteriser and Gecko falls
// back), but safe is not proven, which is why it is not the default."

    seed_block ffstart-core-v1 <<'PREFS'
// ffstart-core-v1 -- the port-level prefs. The marker line is what makes this
// block reach a profile that already exists; bump the version to re-seed it
// after changing a VALUE here.
// #645: the mouse-move black-content flicker is fixed in SOURCE by patch 0022
// (WindowSurfaceCairo::Lock copies the previous ring slot forward, so WebRender's
// partial present composites onto last frame's pixels — the persistence its Draw
// path assumes — instead of the ring's ~3-frame-old / freshly-black slot).
//
// There is deliberately NO pref here. The earlier mitigation
// `gfx.webrender.max-partial-present-rects=0` was a MECHANICAL NO-OP on this
// build: it feeds gfxVars::WebRenderMaxPartialPresentRects(), read ONLY by
// RenderCompositorANGLE/EGL/OGL. The fasadas path runs RenderCompositorSWGL,
// whose Native/SwCompositor arm hardcodes max_partial_present_rects=1 and never
// reads that var — which is why the flicker survived the pref. Nothing relies on
// it after 0022; see ports/firefox/patches/0022 for the full derivation.
// No session restore prompts on a crashed profile — a kiosk-grade default
// while the port stabilises; remove when crash-free runs are the norm.
user_pref("browser.sessionstore.resume_from_crash", false);
// #580: the content-process sandbox blocks the syscall a Web Content process
// needs to hand its rendered scene to the parent compositor, so EVERY remote
// page rendered WHITE (content-process content only — parent-rendered chrome,
// file:// and data: always showed). Proven on the Dell 2026-08-28: with the
// sandbox off, example.com renders in a content process and the YouTube watch
// page plays. The Linux seccomp policy under security/sandbox/linux/ has no
// AnotherOS arm; until it does, the sandbox cannot stay on. Level 0 = off.
user_pref("security.sandbox.content.level", 0);
// A from-scratch OS with SOFTWARE video decode is much slower than the
// ProcessHangMonitor assumes: a Web Content process busy decoding is flagged
// "unresponsive" and SIGKILLed mid-decode, so the <video> never advances past a
// buffering spinner (measured on the Dell 2026-08-28: content pid killed by the
// parent hang monitor; disabling it let the target video LOAD its first frame).
// The processes are slow, not deadlocked, so turning the monitor off is correct
// here rather than a mask.
user_pref("dom.ipc.processHangMonitor", false);
user_pref("dom.ipc.reportProcessHangs", false);
// #602: YouTube video is VP9, and Firefox's RDD tries VA-API HARDWARE decode
// first. VA-API is #429 (not yet implemented), so the /dev/dri ioctls answer
// ENOSYS and avcodec_send_packet fails with "Function not implemented" — every
// video died on the DECODE while AAC audio (no hwaccel path) decoded fine.
// Proven on the Dell 2026-08-29: forcing SOFTWARE decode makes VP9 decode in
// ffvpx and the target video PLAYS (fullscreen, frames advancing). Remove when
// the VA-API backend (#429) lands.
user_pref("media.hardware-video-decoding.enabled", false);
user_pref("media.ffmpeg.vaapi.enabled", false);
// #605: cubeb AudioIPC read media.audioipc.shm_area_size as 0, so the audio
// server could not size its shared-memory ring and the AudioIPC processes were
// SIGKILLed in a storm. Pinning a real ring size stops the deaths (measured on
// the Dell 2026-08-29: 0 kills/run vs many). 2 MiB matches the upstream default
// this build reads as 0.
user_pref("media.audioipc.shm_area_size", 2097152);
PREFS

    # AUDIO OUT (#605). Proven on the Dell 2026-09-06 and not guessed at.
    seed_block ffstart-audio-oss-v1 <<'PREFS'
// ffstart-audio-oss-v1 -- #605: run cubeb IN PROCESS, not through AudioIPC.
//
// With AudioIPC (the default, media.cubeb.sandbox=true) a <audio> element on
// this OS reaches readyState 4, fires `playing`, reports paused=false -- and
// its currentTime STAYS AT 0 for thirty seconds while nothing ever opens
// /dev/dsp. A media clock pinned at zero on a stream that says it is playing is
// what an output stream that was never started looks like.
//
// Measured, same page, same build, one pref apart:
//   media.cubeb.sandbox=true    ct=0 after 30 s, no /dev/dsp holder, no new
//                               HDA stream.
//   media.cubeb.sandbox=false   ct 0.096 -> 1.106 (the clock RUNS), and the
//                               kernel logs
//                                 audio: HDA PCM stream RUN rate=44100 ch=2 bits=32
//                               which is Firefox's own stereo output and not
//                               the boot chime (44100/ch=1/8-bit).
//
// So the OSS backend and the kernel's /dev/dsp both work; it is the REMOTING
// that never starts the stream. media.audioipc.shm_area_size (seeded above) had
// already stopped the audio server being SIGKILLed in a storm -- that fix holds
// and is not undone by this; it simply was not sufficient, because a server
// that stays alive still has to start a stream.
//
// Remove both of these when AudioIPC works here; they are a route around a
// broken path, not a property of the platform, and saying so is the difference
// between a workaround and a lie.
user_pref("media.cubeb.sandbox", false);
user_pref("media.audioipc.enabled", false);
PREFS

    # WebGL on the GPU (see the header).
    seed_block ffstart-webgl-gpu <<'PREFS'
// ffstart-webgl-gpu — WebGL on the GPU through Gecko's own EGL context.
// The gtk GfxInfo's glxtest child cannot succeed on a fasadas display, and a
// failed glxtest blocks FEATURE_WEBGL_USE_HARDWARE by default, which sends
// GLLibraryEGL to its software EGL-device arm (softpipe). This is the
// downloadable-blocklist per-feature override, honoured on release builds
// (gfx.blocklist.all is compiled out there); 1 = FEATURE_STATUS_OK.
user_pref("gfx.blacklist.webgl-use-hardware", 1);
user_pref("webgl.force-enabled", true);
user_pref("webgl.disabled", false);
// DMABuf is Wayland/GL-present-path plumbing; the fasadas present path is
// CPU scanout, and its device open walks sysfs. Keep it off explicitly.
user_pref("widget.dmabuf.enabled", false);
PREFS
    exec "$HERE/firefox" --profile "$PROFILE" "$@"
fi
exec "$HERE/firefox" "$@"
