#!/usr/bin/env node
'use strict'

const fs = require('fs')
const browserify = require('browserify')
const watchify = require('watchify')
const exorcist = require('exorcist')
const program = require('commander')

const BUILD_DIR = 'dist'

function compile(watching) {
  if (!fs.existsSync(BUILD_DIR)) {
    console.log(`Creating ./${BUILD_DIR}`)
    fs.mkdirSync(BUILD_DIR)
  }
  console.log('Building dist/fusion.js and dist/fusion.js.map')
  let bundler = browserify({
    cache: {},
    packageCache: {},
    plugin: [ watchify ],
    debug: true,
  }).require('./src/index.js', { expose: 'Fusion' })
    .transform('babelify', {
    // All source files need to be babelified first
      sourceMapRelative: '.', // source maps will be relative to this dir
    })
    .transform('uglifyify', {
      // uglify all sources, not just application code
      global: true,
    })

  if (watching) {
    bundler.on('update', function() {
      console.log('-> bundling...')
      rebundle(bundler)
    })
    bundler.on('log', msg => {
      console.log(msg)
      console.log('Watching for changes...')
    })
  } else {
    bundler.on('log', msg => {
      console.log(msg)
      bundler.close()
    })
  }

  rebundle(bundler)
}

function rebundle(bundler) {
  bundler.bundle()
    .on('error', err => {
      console.error(err)
      bundler.emit('end')
    })
    // exorcist splits out map to a separate file
    .pipe(exorcist(`${BUILD_DIR}/fusion.js.map`))
    // The unmapped remainder is the code itself
    .pipe(fs.createWriteStream(`${BUILD_DIR}/fusion.js`), 'utf8')
}

program
  .version('0.0.1')
  .option('-w, --watch', 'Watch directory for changes')
  .parse(process.argv)

compile(program.watch)

@@ -231,16 +231,260 @@
 'dist'%0A%0A
+program%0A  .version('0.0.1')%0A  .option('-w, --watch', 'Watch directory for changes')%0A  .option('-U, --no-uglify', %60Don't uglify output%60)%0A  .option('-S, --no-sourcemaps', %60Don't output sourcemaps%60)%0A  .parse(process.argv)%0A%0Acompile(program.watch)%0A%0A
 function
@@ -614,16 +614,46 @@
 IR)%0A  %7D%0A
+  if (program.sourcemaps) %7B%0A  
   consol
@@ -708,16 +708,74 @@
 s.map')%0A
+  %7D else %7B%0A    console.log('Building dist/fusion.js')%0A  %7D%0A
   let bu
@@ -869,20 +869,34 @@
  debug: 
-true
+program.sourcemaps
 ,%0A  %7D).r
@@ -1100,28 +1100,70 @@
  dir%0A    %7D)%0A
-    
+%0A  if (program.uglify) %7B%0A    bundler = bundler
 .transform('
@@ -1253,24 +1253,28 @@
 true,%0A    %7D)
+%0A  %7D
 %0A%0A  if (watc
@@ -1967,136 +1967,4 @@
 )%0A%7D%0A
-%0Aprogram%0A  .version('0.0.1')%0A  .option('-w, --watch', 'Watch directory for changes')%0A  .parse(process.argv)%0A%0Acompile(program.watch)%0A

Allow disabling uglify and source maps