#!/usr/bin/env node

var fs = require('fs')
var path = require('path')
var patch = require('fast-json-patch')
var unique = require('array-unique')
var exec = require('child_process').exec

var pkgpath = path.resolve(__dirname, '../package.json')
var pkg = require(pkgpath)
var tpkg = require(path.resolve(__dirname, '../node_modules/tape/package.json'))

var dev = pkg.devDependencies
var diff = unique(patch
  .compare(dev, tpkg.dependencies)
  .concat(patch.compare(dev, tpkg.devDependencies))
  .filter(function (op) {
    return op.op !== 'remove'
  })
)

if (!diff.length) process.exit(0)

patch.apply(dev, diff)

try {
  var npkg = JSON.stringify(pkg, null, 2)
  fs.writeFileSync(pkgpath, npkg, 'utf8')
  exec('npm install', function (err) {
    if (err) process.stderr.write(err.message + '\n')
  })
} catch (err) {
  process.stderr.write(err.message + '\n')
}
