/* eslint no-console: off */
const path = require("path");
const webpack = require("webpack");
const CompressionPlugin = require('compression-webpack-plugin');
const fs = require('fs');
const utils = require('./cli/utils');


/* Webpack config generator */

const generateConfig = ({extensionPath, devMode=false, customOutputPath, analyzeBundle=false}) => {
  utils.verbose(`Generating webpack config. Extensions? ${!!extensionPath}. devMode: ${devMode}`);

  /* which directories should be parsed by babel and other loaders? */
  const directoriesToTransform = [path.join(__dirname, 'src')];

  /* webpack alias' used in code import / require statements */
  const aliasesToResolve = {
    "@extensions": '.', /* must provide a default, else it won't compile */
    "@auspice": path.join(__dirname, 'src'),
    "@libraries": path.join(__dirname, 'node_modules')
  };

  let extensionData;
  if (extensionPath) {
    // console.log("BUILDING WITH EXTENSIONS");
    const dir = path.resolve(__dirname, path.dirname(extensionPath));
    aliasesToResolve["@extensions"] = dir;
    directoriesToTransform.push(dir);
    // console.log("directoriesToTransform", directoriesToTransform);
    extensionData = JSON.parse(fs.readFileSync(extensionPath, {encoding: 'utf8'}));
    // console.log("extensionData", extensionData);
  }

  /* plugins */
  /* inject strings into the client-accessible process.env */
  const pluginProcessEnvData = new webpack.DefinePlugin({
    "process.env": {
      NODE_ENV: devMode ? JSON.stringify("development") : JSON.stringify("production"),
      EXTENSION_DATA: JSON.stringify(extensionData)
    }
  });
  /* gzip everything - https://github.com/webpack-contrib/compression-webpack-plugin */
  const pluginCompress = new CompressionPlugin({
    asset: "[path].gz[query]",
    algorithm: "gzip",
    test: /\.js$|\.css$|\.html$/,
    threshold: 10240,
    minRatio: 0.8
  });
  const plugins = devMode ? [
    new webpack.HotModuleReplacementPlugin(),
    pluginProcessEnvData,
    new webpack.NoEmitOnErrorsPlugin()
  ] : [
    pluginProcessEnvData,
    new webpack.optimize.AggressiveMergingPlugin(), // merge chunks - https://github.com/webpack/docs/wiki/list-of-plugins#aggressivemergingplugin
    pluginCompress
  ];

  if (analyzeBundle) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; // eslint-disable-line
    plugins.push(new BundleAnalyzerPlugin());
  }

  const entry = [
    "babel-polyfill",
    "./src/index"
  ];
  if (devMode) {
    entry.splice(1, 0, "webpack-hot-middleware/client");
  }

  /* Where do we want the output to be saved?
   * For development we use the (virtual) "devel" directory
   * Else we must choose to save it in the CWD or the source
   */
  const outputPath = devMode ?
    path.resolve(__dirname, "devel") : // development: use the (virtual) "devel" directory
    customOutputPath ?
      path.resolve(customOutputPath, "dist") :
      path.resolve(__dirname, "dist");
  utils.verbose(`Webpack writing output to: ${outputPath}`);

  const config = {
    mode: devMode ? 'development' : 'production',
    context: __dirname,
    entry,
    output: {
      path: outputPath,
      filename: "auspice.bundle.js",
      chunkFilename: 'auspice.chunk.[name].bundle.js',
      publicPath: "/dist/"
    },
    resolve: {
      alias: aliasesToResolve
    },
    node: {
      fs: 'empty'
    },
    plugins,
    optimization: {
      minimize: !devMode
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'babel-loader',
          include: directoriesToTransform,
          options: {
            cwd: path.resolve(__dirname)
          }
        },
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"]
        },
        {
          test: /\.(gif|png|jpe?g|svg|woff2?|eot|otf|ttf)$/i,
          use: "file-loader",
          include: [
            ...directoriesToTransform,
            path.join(__dirname, 'node_modules/font-awesome'),
            path.join(__dirname, 'node_modules/leaflet'),
            path.join(__dirname, 'node_modules/typeface-lato')
          ]
        }
      ]
    }
  };

  config.devtool = 'cheap-module-source-map';

  return config;
};

module.exports = {default: generateConfig};

@@ -587,16 +587,944 @@
 rc')%5D;%0A%0A
+  /* which font modules need to be able to be loaded by auspice? */%0A  const fontModules = %5B%22font-awesome%22, %22leaflet%22, %22typeface-lato%22%5D;%0A  /* note that the directory structure is different depending on whether auspice%0A  is installed from source, a global npm install or a project's dependency. E.g.%0A  Global install & from source: %60$%7B__dirname%7D/node_modules/font-awesome%60%0A  Project dependency:           %60$%7B__dirname%7D/../font-awesome%60%0A  This implementation is a short-term solution and should be improved */%0A  let fileLoaderDirectoriesToTransform;%0A  if (fs.existsSync(path.join(__dirname, %22node_modules%22, fontModules%5B0%5D))) %7B%0A    // global npm install or install from source%0A    fileLoaderDirectoriesToTransform = fontModules.map((d) =%3E path.join(__dirname, %22node_modules%22, d));%0A  %7D else %7B%0A    // auspice is a project's dependency%0A    fileLoaderDirectoriesToTransform = fontModules.map((d) =%3E path.join(__dirname, %22..%22, d));%0A  %7D%0A%0A
   /* web
@@ -4885,179 +4885,43 @@
     
-path.join(__dirname, 'node_modules/font-awesome'),%0A            path.join(__dirname, 'node_modules/leaflet'),%0A            path.join(__dirname, 'node_modules/typeface-lato')
+...fileLoaderDirectoriesToTransform
 %0A   

Fix webpack transforms for different install methods