Getting Calibre working with camoufox and browserforge

Hi! I’m pretty new on Nixos, so this might be messy, so this is as much guide to getting Calibre working as a question on how I should do this more elegantly.

The Calibre Camoufox-functionality needs a local version of camoufox on Nix, the bundled one wont have a working environment. I created a hacky overlay (the first one so far) to provide Calibre access to camoufox and browserforge. This is for Calibre 9.17

Feast your eyes on this and despair!

(final: prev: {
  calibre = prev.calibre.overrideAttrs (old:
   {
    buildInputs = old.buildInputs ++ [final.camoufox final.python314Packages.browserforge];

    postPatch =
      (old.postPatch or "")
      + ''
        unwrapped=$(grep -o '/nix/store/[^/"]*camoufox-unwrapped[^/"]*' ${final.camoufox}/bin/camoufox | head -n1)
        test -n "$unwrapped" || { echo "could not find unwrapped camoufox"; exit 1; }

        substituteInPlace setup/resources.py \
          --replace-fail "if not opts.system_camoufox:" "if False:" \
          --replace-fail "parts = opts.system_camoufox.split(os.pathsep)" "parts = '$unwrapped/bin/camoufox:$unwrapped/lib/camoufox'.split(os.pathsep)"
      '';
    preFixup =
      ''
        qtWrapperArgs+=(
          --prefix PYTHONPATH : ${final.python314Packages.makePythonPath [final.python314Packages.browserforge]}
          --prefix LD_LIBRARY_PATH : ${final.lib.makeLibraryPath [
          final.gtk3
          final.glib
          final.dbus-glib
          final.libGL
          final.libxkbcommon
          final.alsa-lib
          final.libpulseaudio
          final.pciutils
          final.libX11
          final.libXtst
          final.libXrandr
          final.libXcomposite
          final.libXdamage
          final.libXfixes
          final.libXcursor
          final.libXi
          final.libxcb
          final.wayland
        ]}
        )
      ''
      + old.preFixup;
  });
})

This might help someone with the same problem, but yes, some questions:

The hacky grep-substitution is because dealing with python whitespace within Nix code was difficult. Is there a better way to do this?

How would I go about bundling camoufox with calibre instead of relying on a system-wide setup?

I know the libraries are excessive, but I didn’t have enough time to build and check for what is needed one library at a time, so I added the some probable ones and decided to get back to it at some point.

edit: didn’t need to set camoufox fonts for functionality, so dropped that