var fs = require('fs')
var path = require('path')
var child_process = require('child_process')
var exec = child_process.exec
var spawn = child_process.spawn

module.exports = function(grunt) {
  grunt.initConfig({
    jshint: {
      options: {
        jshintrc: true
      },
      lib: ['lib/**/*.js']
    },
    watch: {
      lib: {
        files: ['lib/**/*.js'],
        tasks: ['jshint', 'test']
      },
      test: {
        files: ['test/**/*.js', 'Gruntfile.js'],
        tasks: ['test']
      }
    }
  })

  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-contrib-jshint')

  grunt.registerTask('test', ['jshint', 'unit'])
  grunt.registerTask('default', ['test'])

  grunt.registerTask('nuke', "Nuke stuff. Don't run this unless you know what you're doing.", function() {
    var steps = ['rm -rf ~/.impromptu', 'git clean -fdx']
    exec(steps.join(' && '))
  })

  // Run the unit tests by spawning an Impromptu server and passing through the 'test' message.
  // This allows us to run the tests in a real-world environment: the database requires an
  // Impromptu server and worker process to work correctly.
  grunt.registerTask('unit', 'Run unit tests.', function() {
    var done = this.async()
    var cmd = "IMPROMPTU_PORT=2934 IMPROMPTU_UNIX_DOMAIN_SOCKET='' impromptu server"

    exec(cmd + ' shutdown', function(err, stdout, stderr) {
      var server = exec(cmd + ' foreground')
      server.stdout.pipe(process.stdout)
      server.stderr.pipe(process.stderr)

      // Grunt is kind of weird here. Passing boolean false to done indicates that
      // there was an error.
      server.on('exit', function(code) {
        done(code === 0)
      })

      setTimeout(function() {
        exec(cmd + ' test')
      }, 1000)
    })
  })
}

@@ -648,16 +648,31 @@
 , 'unit'
+, 'check-types'
 %5D)%0A  gru
@@ -1791,11 +1791,538 @@
  %7D)%0A  %7D)
+%0A%0A  grunt.registerTask('check-types', 'Checks the types of Impromptu using Closure Compiler.', function() %7B%0A    var done = this.async()%0A    var checkTypes = exec('./node_modules/.bin/closure-npc', function(err, stdout, stderr) %7B%0A      var results = stderr.trim().split('%5Cn').pop()%0A      var errorMatch = /(%5Cd+) error%5C(s%5C)/.exec(results)%0A      var succeeded = errorMatch && parseInt(errorMatch%5B1%5D, 10) === 0%0A      done(succeeded)%0A    %7D)%0A%0A    checkTypes.stdout.pipe(process.stdout)%0A    checkTypes.stderr.pipe(process.stderr)%0A  %7D)
 %0A%7D%0A

Add Grunt task to check types.