# SPDX-FileCopyrightText: 2025 toastal <toastal@posteo.net>
# SPDX-License-Identifier: MPL-2.0
{
  lib,
  linkFarm,
  stdenvNoCC,
  runCommand,
  lightningcss,
  optipng,
  scour,
  tup,
  precompressBrotli ? false,
  parallel,
  brotli,

  # project packages
  mplus-webfonts,
  open-props,
}:

let
  fs = lib.fileset;
  inherit (import ../utils.nix { inherit lib parallel; }) beparallel;
in
stdenvNoCC.mkDerivation (finalAttrs: {
  name = "w3m-assets";

  src = fs.toSource {
    root = ../../.;
    fileset = fs.unions [
      ../../.browserslistrc
      ../../Tuprules.tup
      ../../assets
      (fs.maybeMissing ../../tup.config)
    ];
  };

  nativeBuildInputs = [
    lightningcss
    optipng
    scour
    tup
  ] ++ lib.optional precompressBrotli brotli;

  outputs = [ "out" ];

  # SOUPAULT_BUILD_DIR needs to be exported so Tup knows where to build.
  # For convenience during development, Nix is used to symlink in the installPhase
  # in Tup. However, we need to prevent this for the Nix build output using an
  # @-variable.
  configurePhase = ''
    export SOUPAULT_BUILD_DIR="$(realpath "$PWD")/build"
    echo "CONFIG_TUP_NIX_LINK=0" >> tup.config
    tupConfigurePhase
  '';

  buildPhase = ''tupBuildPhase'';

  installPhase =
    ''
      cp -Tfr "$SOUPAULT_BUILD_DIR/assets" $out
      ln -s ${open-props.override { inherit precompressBrotli; }} $out/open-props
      ln -s ${mplus-webfonts} $out/m+
    ''
    +
      lib.optionalString precompressBrotli # bash
        ''
          find $out -type f -iname "*.css" -o -iname "*.js" -o -iname "*.svg" \
            | ${beparallel ''brotli --keep --quality=11 --output={}.br {}''}
        '';

  meta = {
    licence = lib.licenses.mpl20;
  };
})
