#!/usr/bin/env node

'use strict'

const fs = require('fs')
const path = require('path')
const process = require('process')
const pretty = require('depmap-errors')

async function findDepmap () {
  return await new Promise((resolve, reject) => {
    let global = path.join(process.cwd(), 'node_modules/depmap')
    fs.stat(global, (err, data) => {
      if (err) resolve('depmap')
      resolve(global)
    })
  })
}

const args = process.argv
const env = process.env.NODE_ENV || ''
const cmds = {
  __usage: 'usage:\n      depmap [option]\n\noptions:',
  compile: '    compile: build the project once. If the build directory is present, will only update the difference',
  watch: '    watch:   continuously compile the project when files are updated',
  help: '    help:    display this dialog'
}

if (args.length < 3 || args[2] === 'help') for (let cmd in cmds) console.log(cmds[cmd])
else {
  let cfg = env ? `config.${env}.js` : 'config.js'
  let opts = {}
  fs.stat(cfg, (err, data) => {
    if (err) {
      pretty.warn('Warning: No config found. Using default config')
    }

    opts = require(path.join(process.cwd(), 'config.js'))

    findDepmap()
      .then(path => {
        let depmap = require(path)
        depmap.build(opts)
          .then(map => depmap[args[2]](map, opts))
          .catch(pretty.error)
      })
      .catch(pretty.error)
  })
}

@@ -188,18 +188,16 @@
 map () %7B
-%0A 
  return 
@@ -936,16 +936,55 @@
 fig.js'%0A
+  cfg = path.join(process.cwd(), cfg)%0A%0A
   let op
@@ -1035,20 +1035,42 @@
 if (
+!
 err) 
-%7B%0A     
+opts = require(cfg)%0A    else
  pre
@@ -1131,73 +1131,8 @@
 ig')
-%0A    %7D%0A%0A    opts = require(path.join(process.cwd(), 'config.js'))
 %0A%0A  
@@ -1158,20 +1158,19 @@
   .then(
-path
+mod
  =%3E %7B%0A  
@@ -1196,20 +1196,19 @@
 require(
-path
+mod
 )%0A      
@@ -1204,24 +1204,56 @@
 mod)%0A       
+ let map%0A        %5B map, opts %5D =
  depmap.buil
@@ -1271,23 +1271,8 @@
     
-   .then(map =%3E
  dep
@@ -1298,40 +1298,8 @@
 pts)
-)%0A          .catch(pretty.error)
 %0A   

switch to sync version of depmap