const path = require('path');
const tools = require('./scripts/utils/tools');
const execa = require('execa');
const fs = require('fs');

console.log('----------------------------------------------');
console.log('Init tools package symlink...');
console.log('----------------------------------------------');

const nmSrcPath = path.join(process.cwd(), 'node_modules');

// for testing purpose standalone mode locally
// const nmSrcPath = path.join('d:/gitlab/zzz-test-package-ui', 'node_modules');
// const nmSrcPath = path.join('d:/gitlab/baep-sample-host-shell-ui', 'node_modules');
// const nmSrcPath = path.join('d:/gitlab/zzz-test-remote-eui18', 'node_modules');
// const nmSrcPath = path.join('d:/gitlab/baep-playground', 'node_modules');
// const nmSrcPath = path.join('d:/gitlab/app-baep-sample-host', 'node_modules');

const euiNmToolsPath = path.join(nmSrcPath, '@eui', 'tools');
const eUIToolsPath = path.join(process.cwd(), 'packages', 'eui-tools');

if (!tools.isDirExists(eUIToolsPath)) {
  return;
}

return Promise.resolve()
  .then(() => {
    if (tools.isDirExists(euiNmToolsPath)) {
      return tools.rimraf(euiNmToolsPath);
    }
  })
  .then(() => {
    if (!tools.isDirExists(path.join(nmSrcPath, '@eui'))) {
      return tools.mkdir(path.join(nmSrcPath, '@eui'));
    }
  })
  .then(() => {
    return tools.link(eUIToolsPath, euiNmToolsPath);
  })
  .then(() => {
      if (!fs.existsSync(path.join(nmSrcPath, '/.bin/eui-scripts.cmd'))) {
          console.log('Building eui-scripts...');
          return execa('npm', ['build', 'node_modules/@eui/tools']);
      }
      return;
  })
  .then(() => {
      console.log('----------------------------------------------');
      console.log('Respository ready to go!');
      console.log('----------------------------------------------');
  })
  .catch((e) => {
      console.log('ERROR initiating repository');
      console.log(e);
  });
