#!/usr/bin/env node
'use strict';
const { resolve } = require('path')
const { spawn } = require('child_process')

const pkg = require(resolve(__dirname, '../package.json'))
const nmBinDir = resolve(__dirname, '../node_modules/.bin/')

const shell = { cmd: 'sh', arg: '-c' }

// replace all @/ to node modules bin dir
const replaceTokens = str => String(str).replace(new RegExp('@\\/', 'gi'), `${nmBinDir}/`)

function runCommand(command, args = '') {
  const proc = spawn(shell.cmd, [shell.arg, `${replaceTokens(command)} ${args}`], {
    env: process.env,
    cwd: process.cwd(),
    stdio: 'inherit',
  })

  proc.on('close', (code) => {
    if (code !== 0) {
      console.log(`command:"${command}" exited with code ${code}`);
    }

    process.exit(code)
  });
}

function runCommandByKey(key, command) {
  const event_name = process.env.npm_lifecycle_event
  const args = process.argv.slice(2);

  if (args.length >= 1) {
    const [name, ...argarr] = args

    if (name === key) {
      return runCommand(command, argarr.join(' '))
    }
  }

  if (args.length === 0 && event_name && event_name === key) {
    return runCommand(command)
  }
}

for (const [key, command] of Object.entries(pkg.pkgTasks)) {
  runCommandByKey(key, command)
}
