#!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const program = require('commander');
const pkg = require('../package.json');
const execa = require('execa');
const chalk = require('chalk');

program
// 版本号
  .version('v' + pkg.version, '-v, --version')
  .usage('run [command] [option]')
  .option('-e --env [env]', 'what env do you want set  ')
  .option('--senv [senv]', 'what egg environment do you want');

program
  .command('dev [options]')
  .description('run project in dev mode');
program
  .command('build [options]')
  .description('build project，only can execute in dashboard or h5');
program
  .command('lint')
  .description('lint project code follow your eslint file');
program
  .command('packageName')
  .description('echo project name');
program
  .command('packageVersion')
  .description('echo project version');
program
  .command('startup:docker')
  .description('startup');
program
  .command('test')
  .description('only can execute in service(egg.js)');
program
  .command('cov')
  .description('only can execute in service(egg.js)');
program
  .command('ci')
  .description('only can execute in service(egg.js)');

program.on('--help', function() {
  console.log('');
  console.log('Examples:');
  console.log('  $ ne run dev -e k1=v1,k2=v2');
});
program.parse(process.argv);
// 类型
program
  .command('run [command]')
  .description('run project')
  .option('-e --env [env]', 'what environment do you want')
  .option('--senv [senv]', 'what egg environment do you want')
  .action(async (command, options) => {
    let projectType = 'dashboard';
    let pkg;
    const cmdObj = require('./command');
    // 确定是否存在package.json
    if (fs.existsSync(path.join(process.cwd(), './package.json'))) {
      // 确定项目类型
      pkg = require(path.join(process.cwd(), './package.json'));
      if (pkg.name.indexOf('dashboard') > -1) {
        projectType = 'dashboard';
      } else if (pkg.name.indexOf('service') > -1) {
        projectType = 'service';
      } else if (pkg.name.indexOf('h5') > -1) {
        projectType = 'h5';
      } else {
        return console.error(chalk.red('ERROR! Other types of project are not supported'));
      }
    } else {
      return console.error(chalk.red('ERROR! No correct project exist or execute path is not correct.'));
    }
    // 确定是否支持该指令
    if (!cmdObj[ projectType ][ command ]) {
      return console.error(chalk.red('ERROR! This command are not supported'));
    }
    if (command !== 'packageVersion' && command !== 'packageName') {
      let shStr = '';
      if (cmdObj[ projectType ][ command ].indexOf('$snyk-token$')) {
        if (process.env.SNYK_TOKEN) {
          const snykReg = new RegExp('\\$snyk-token\\$', 'ig');
          cmdObj[ projectType ][ command ] = cmdObj[ projectType ][ command ].replace(snykReg, process.env.SNYK_TOKEN);
        }
      }
      if (cmdObj[ projectType ][ command ].indexOf('$env$') > -1) {
        let env = '';
        if (options.parent.env) {
          const envArr1 = options.parent.env.split(',');
          for (const i in envArr1) {
            if (i !== 'SNYK_TOKEN') {
              envArr1[i] = '--' + envArr1[i];
            } else {
              const snykReg = new RegExp('\\$snyk-token\\$', 'ig');
              cmdObj[ projectType ][ command ] = cmdObj[ projectType ][ command ].replace(snykReg, envArr1[i]);
            }
          }
          env += envArr1.join(' ');
        }
        if (pkg['ne-env-' + command]) {
          const envArr = [];
          for (const i in pkg['ne-env-' + command]) {
            if (env.indexOf(i + '=' + pkg['ne-env-' + command]) < 0) {
              if (i !== 'SNYK_TOKEN') {
                envArr.push(i + '=' + pkg['ne-env-' + command][ i ]);
              } else {
                const snykReg = new RegExp('\\$snyk-token\\$', 'ig');
                cmdObj[ projectType ][ command ] = cmdObj[ projectType ][ command ].replace(snykReg, pkg['ne-env-' + command][ i ]);
              }
            }
          }
          env += ' ' + envArr.join(' ');
        }
        const tarReg1 = new RegExp('\\$env\\$', 'ig');
        shStr = cmdObj[ projectType ][ command ].replace(tarReg1, env);
      } else {
        shStr = cmdObj[ projectType ][ command ];
      }
      if (shStr.indexOf('$senv$') > -1) {
        let senv = '';
        if (options.parent.senv) {
          const senvArr = options.parent.senv.split(',');
          for (const i in senvArr) {
            senvArr[i] = '--' + senvArr[i];
          }
          senv += senvArr.join(' ');
        }
        if (pkg['ne-senv-' + command]) {
          const senvArr2 = [];
          for (const i in pkg['ne-senv-' + command]) {
            if (senv.indexOf('--' + i + '=' + pkg['ne-senv-' + command][ i ]) < 0) {
              senvArr2.push('--' + i + '=' + pkg['ne-senv-' + command][ i ]);
            }
          }
          senv += ' ' + senvArr2.join(' ');
        }
        const tarReg2 = new RegExp('\\$senv\\$', 'ig');
        shStr = shStr.replace(tarReg2, senv);
      }
      fs.writeSync(1, '\n');
      console.log('> ' + shStr);
      fs.writeSync(1, '\n');
      execa.shell(shStr, { stdio: 'inherit' });
    } else {
      if (command === 'packageVersion') {
        fs.writeSync(1, pkg.version);
      } else {
        fs.writeSync(1, pkg.name);
      }
    }
  });


program.parse(process.argv);
