/**
 * Module dependencies
 */

const path = require('path');
const execSync = require('child_process').execSync;

/**
 * Load configuration
 */

let workingDirectory = path.resolve(`${__dirname}/../`);

  /**
   * Build client files with Webpack
   */

try {
  console.info('-- bundling js and css...');
  const out = execSync(
    'webpack -p --config webpack.build.config.js',
    {
      cwd: workingDirectory,
      env: { NODE_ENV: 'production', PATH: process.env.PATH },
      uid: process.env.UID
    }
  );
  const parsedOut = out.toString().split('ERROR');
  if (parsedOut.length > 1) {
    parsedOut.shift();
    console.error(`ERROR ${parsedOut.join('ERROR')}`);
    process.exit(1);
  } else {
    console.info('-- finished bundling client files');
  }
} catch (err) {
  console.error(err);
  process.exit(1);
}

/**
 * Build server files with Babel
 */

try {
  console.info('-- building lib...');
  workingDirectory = path.resolve(`${workingDirectory}/src`);
  const outBabel = execSync(
    'babel ./ --out-dir ../lib',
    {
      cwd: workingDirectory,
      env: { NODE_ENV: 'production', PATH: process.env.PATH },
      uid: process.env.UID
    }
  );
  const parsedOutBabel = outBabel.toString().split('ERROR');
  if (parsedOutBabel.length > 1) {
    parsedOutBabel.shift();
    console.error(`ERROR ${parsedOutBabel.join('ERROR')}`);
    process.exit(1);
  } else {
    console.info('-- finished building lib');
  }
} catch (err) {
  console.error(err);
  process.exit(1);
}
