{ stdenv, mkYarnModules, nodejs, cleanSchildichatDesktopSource, schildichat-desktop-src ? ../. }:

let
  packageJSON = schildichat-desktop-src + "/element-web/package.json";
  yarnLock = schildichat-desktop-src + "/element-web/yarn.lock";
  version = builtins.fromJSON (builtins.readFile packageJSON).version;

  modules = mkYarnModules {
    name = "schildichat-web-modules-${version}";
    inherit packageJSON yarnLock;
  };
  
in stdenv.mkDerivation {
  pname = "schildichat-web";
  inherit version;
  src = cleanSource schildichat-desktop-src;
  buildInputs = [ nodejs ];

  configurePhase = ''
    patchShebangs .
    cp configs/sc/config.json element-web/
    cp -r ${modules}/node_modules .
    chmod u+rwX -R node_modules
    rm -rf node_modules/matrix-react-sdk

    ln -s $PWD/matrix-react-sdk node_modules/
    ln -s $PWD/node_modules matrix-react-sdk/
    ln -s $PWD/node_modules element-web/
  '';

  buildPhase = ''
    pushd matrix-react-sdk
    node_modules/.bin/reskindex -h ../element-web/src/header
    popd
    pushd element-web
    node scripts/copy-res.js
    node_modules/.bin/reskindex -h src/header
    node_modules/.bin/webpack --progress --mode production
    popd
  '';

  installPhase = ''
    cp -r element-web/webapp $out
  '';

  passthru.modules = modules;
}