fs = require 'fs'
{exec, spawn, execSync} = require 'child_process'

# All coffeescript files required.
FILES = [
  'shims.coffee'
  'util.coffee'
  'proxypair.coffee'
  'websocket.coffee'
  'broker.coffee'
  'ui.coffee'
  'snowflake.coffee'
]
FILES_SPEC = [
  'spec/util.spec.coffee'
  'spec/ui.spec.coffee'
  'spec/broker.spec.coffee'
  'spec/proxypair.spec.coffee'
  'spec/snowflake.spec.coffee'
]
FILES_ALL = FILES.concat FILES_SPEC
OUTFILE = 'build/snowflake.js'
STATIC = 'static'

copyStaticFiles = ->
  exec 'cp ' + STATIC + '/* build/'
  exec 'cp lib/modernizr.js build/'

compileCoffee = ->
  exec 'cat ' + FILES.join(' ') + ' | coffee -cs > ' + OUTFILE, (err, stdout, stderr) ->
    throw err if err

task 'test', 'snowflake unit tests', ->
  exec 'mkdir -p test'
  exec 'jasmine init >&-'
  # Simply concat all the files because we're not using node exports.
  jasmineFiles = FILES_ALL
  outFile = 'test/bundle.spec.coffee'
  exec 'cat ' + jasmineFiles.join(' ') +  ' | cat > ' + outFile
  execSync 'coffee -cb ' + outFile
  spawn 'jasmine', ['test/bundle.spec.js'], {
    stdio: 'inherit'
  }

task 'build', 'build the snowflake proxy', ->
  exec 'mkdir -p build'
  copyStaticFiles()
  compileCoffee()
  console.log 'Snowflake prepared.'

task 'lint', 'ensure idiomatic coffeescript', ->
  spawn 'coffeelint', FILES_ALL, {
    file: 'coffeelint.json'
    stdio: 'inherit'
  }

task 'clean', 'remove all built files', ->
  exec 'rm -r build'
