private: Yes


{ stdenv, fetchFromGitHub, callPackage, runCommand
, bash, yarn
, production ? false }:

let
  target = if production then "prod" else "dev";
  pkgInfo = stdenv.lib.importJSON ./package.json;
  src = ./.;
  yarn2nixSrc = fetchFromGitHub {
    owner  = "Profpatsch";
    repo   = "yarn2nix";
    rev    = "3e3bc88398ef73f964c4dfe238fa80e65bf7fbc6";
    sha256 = "142h572gwfg8d2pkbwm5s0cmxvw8ny8kc80vl0wrw45p6x335bgf";
  };
  yarn2nix = import yarn2nixSrc { };
  yarn2nix-lib = callPackage (yarn2nixSrc + /nix-lib) { inherit yarn2nix; };
  depsNix = runCommand "deps.nix" { } ''
    ${yarn2nix}/bin/yarn2nix ${src}/yarn.lock > $out
  '';
  template = runCommand "template.nix" { } ''
    ${yarn2nix}/bin/yarn2nix --template ${src}/package.json > $out
  '';
  node_modules = yarn2nix-lib.linkNodeDeps {
    inherit (pkgInfo) name;
    dependencies = (yarn2nix-lib.callTemplate
                     template
                     (yarn2nix-lib.buildNodeDeps (callPackage depsNix { }))).nodeBuildInputs;
  };

in

stdenv.mkDerivation rec {
  pname = pkgInfo.name;
  inherit (pkgInfo) version;
  inherit src;

  buildInputs = [ yarn ];

  phases = [ "unpackPhase" "patchPhase" "buildPhase" "installPhase" ];

  postPatch = ''
    substituteInPlace ./package.json \
      --replace node_modules "${node_modules}"
  '';

  buildPhase = ''
    # temporary $HOME for yarn config
    export HOME=$(pwd)/yarn_home
    mkdir -p $HOME
    yarn config --offline set script-shell "${bash}/bin/bash"

    # binaries of deps.nix
    export PATH="${node_modules}/.bin:$PATH"

    # browserify won't look in NODE_PATH for modules
    ln -s ${node_modules} node_modules
    yarn run --offline build:assets
    yarn run --offline build:${target}
  '';

  installPhase = ''
    mkdir -p $out/share/
    cp -R dist $out/share/${pname}
  '';
}