# SPDX-FileCopyrightText: 2022-2024 Sarah Vaupel <sarah.vaupel@uniworx.de>, Gregor Kleen <gregor.kleen@ifi.lmu.de>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

{ frontendSource, ... }: final: prev:
let
  pname = "uniworx-frontend";
  # extract the version from package.json (ensuring these never get out of sync)
  version = (builtins.fromJSON (builtins.readFile ./../../package.json)).version;

  # grab our dependencies
  deps = prev.mkYarnModules {
    inherit pname version;
    packageJSON = ./../../package.json;
    yarnLock = ./../../yarn.lock;
    yarnNix = ./../../yarn.nix;
  };
  setupNodeDeps = ''
    ln -s ${final.uniworxNodeDependencies}/lib/node_modules ./node_modules
    export PATH="${final.uniworxNodeDependencies}/bin:$PATH"
  '';
in {
  uniworxFrontend = prev.stdenv.mkDerivation {
    inherit pname version;

    srcs = [frontendSource prev.uniworxWellKnown];
    sourceRoot = "source";

    phases = ["unpackPhase" "configurePhase" "checkPhase" "buildPhase" "installPhase"];

    # No build dependencies, all work has been done for you already by mkYarnModules
    nativeBuildInputs = [ ];
    buildInputs = [ ];

    postUnpack = ''
      ${final.xorg.lndir}/bin/lndir -silent ../uniworx-well-known $sourceRoot
    '';

    preBuild = setupNodeDeps;
    buildPhase = ''
      runHook preBuild

      webpack --progress

      runHook postBuild
    '';

    # Grab the dependencies from the above mkYarnModules derivation
    configurePhase = ''
      mkdir -p $out/bin
      ln -s ${deps}/node_modules $out
    '';

    preCheck = ''
      ${setupNodeDeps}
      export FONTCONFIG_FILE="${final.fontconfig.out}/etc/fonts/fonts.conf"
      export FONTCONFIG_PATH="${final.fontconfig.out}/etc/fonts/"
      export CHROME_BIN="${final.chromium}/bin/chromium-browser"
    '';
    checkPhase = ''
      runHook preCheck

      eslint frontend/src
      karma start --conf karma.conf.js

      runHook postCheck
    '';

    installPhase = ''
      mkdir -p $out $out/config
      cp -r --reflink=auto well-known static $out
      cp -r --reflink=auto config/webpack.yml $out/config
    '';

    passthru.check = final.uniworxFrontend.overrideAttrs (oldAttrs: {
      name = "${oldAttrs.name}-check";
      phases = ["unpackPhase" "buildPhase"];
      buildPhase = ''
        mkdir $out
        ( ${oldAttrs.checkPhase} ) | tee $out/test-stdout
      '';
    });

    # Skip the unpack step (mkDerivation will complain otherwise)  
    dontUnpack = true;
  };
}
