{ pkgs ? import <nixpkgs> {} }:

let
  # dependency: SCCD compiler
  sccd = builtins.fetchGit {
    url = "https://msdl.uantwerpen.be/git/arys/sccd.git";
    ref = "dev";
    rev = "8e63f96438fdc84e74389daa11bcd4bb332ecedb";
  };

  sccdJsRuntimePath = "${sccd.outPath}/docs/runtimes/javascript";

  # dependency: Dependency-aware Operation History (DOH)
  doh = import (builtins.fetchGit {
    url = "https://msdl.uantwerpen.be/git/jexelmans/doh";
    ref = "master";
    rev = "8c1d7e435f7d1e412436800de3a7f0aa0c640992";
  }) {};


  commonSrc = ../src/collab/common;
  serverSrc = ../src/collab/server;

  node = pkgs.nodejs-slim-18_x;
  #node = pkgs.nodejs-slim;

  # 
  npmDeps = import ./npm_deps {};

in rec {
  # get a development shell
  shell = pkgs.mkShell {
    buildInputs = [
      # for SCCD
      pkgs.python39

      # to run a test server (for development)
      node

      pkgs.nodePackages.browserify

      # to build (produce minified JS) - because Ant output is placed in the same directories as the source, this part of the build cannot be Nixified.
      pkgs.ant
      pkgs.jre8_headless
    ];

    # find our NPM dependencies (for development and for building a Docker container)
    NODE_PATH = "${npmDeps.nodeDependencies}/lib/node_modules:${doh.package}/lib/node_modules:${sccdJsRuntimePath}";

    # find SCCD compiler
    PYTHONPATH = sccd.outPath;
  };

  # build static web app - can host this with any static file server (e.g. nginx, apache, ...)
  # 'collab' plugin requires a special backend server though.
  staticWebApp = derivation {
    name = "drawio-static";
    system = builtins.currentSystem;

    coreutils = pkgs.coreutils;
    src_webapp = ../src/main/webapp;

    builder = "${pkgs.bash}/bin/bash";
    args = [ ./static-webapp-builder.sh ];
  };

  # build a Node-based web server that hosts the application (statically) and also runs a websocket endpoint for the 'collab' plugin.
  server = derivation {
    name = "drawio-server";
    system = builtins.currentSystem;

    inherit node staticWebApp commonSrc serverSrc;

    coreutils = pkgs.coreutils;

    node_path = "${npmDeps.nodeDependencies}/lib/node_modules:${commonSrc}";

    builder = "${pkgs.bash}/bin/bash";
    args = [ ./server-builder.sh ];
  };

  # build a Docker container with everything cooked in.
  dockerServer = pkgs.dockerTools.buildImage {
    name = "drawio-server";
    contents = server;
    config = {
      Cmd = [ "bin/drawioserver" "--state-dir" "/state"];
      Volumes = { "/state" = {}; };
      ExposedPorts = { "8700/tcp" = {}; };
    };
  };
}
