#!/usr/bin/env node
/**
 * Copyright 2019 The Kubernetes Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.main = void 0;
var _path = require("path");
var colors = _interopRequireWildcard(require("colors/safe"));
var _child_process = require("child_process");
var _fsExtra = require("fs-extra");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
/** simple message notifying the user that we are creating an asset */
const creating = (what, how = 'creating') => {
  console.log(colors.green('✓') + ` ${how} ${what}`);
};
/** simple message notifying the user that we are NOT creating an asset */
const notCreating = what => {
  console.log(colors.dim('-') + ' not creating ' + what);
};
const tsconfig = {
  extends: './node_modules/@kui-shell/builder/tsconfig-base.json',
  references: [{
    path: 'plugins/plugin-sample'
  }]
};
/**
 * Copy a directory
 *
 * @param breadcrumb specifies a require-able breadcrumb within the
 * directory to the copied
 * @param target the path to the target directory
 *
 */
const copyDirectory = (breadcrumb, target, force) => __awaiter(void 0, void 0, void 0, function* () {
  const targetExists = yield (0, _fsExtra.pathExists)(target);
  if (!targetExists || force) {
    // note fs-extra's copy of directories copies the *contents*
    if (!targetExists) {
      yield (0, _fsExtra.mkdir)(target);
    }
    const source = (0, _path.dirname)(require.resolve(breadcrumb));
    yield (0, _fsExtra.copy)(source, target, {
      preserveTimestamps: true
    });
    creating(target);
  } else {
    notCreating(target);
  }
});
const main = argv => __awaiter(void 0, void 0, void 0, function* () {
  const force = !!argv.find(_ => _ === '-f' || _ === '--force');
  if (!(yield (0, _fsExtra.pathExists)('plugins'))) {
    yield (0, _fsExtra.mkdir)('plugins');
    creating('plugins directory');
  } else {
    notCreating('plugins directory');
  }
  if (!(yield (0, _fsExtra.pathExists)('packages/app/src'))) {
    yield (0, _fsExtra.mkdirp)('packages/app/src');
    creating('packages/app/src directory');
  } else {
    notCreating('packages/app/src directory');
  }
  if (!(yield (0, _fsExtra.pathExists)('packages/app/src/main.ts'))) {
    yield (0, _fsExtra.writeFile)('packages/app/src/main.ts', '// intentionally blank');
    creating('packages/app/src directory');
  } else {
    notCreating('packages/app/src directory');
  }
  if (!(yield (0, _fsExtra.pathExists)('tsconfig.json'))) {
    yield (0, _fsExtra.writeFile)('tsconfig.json', JSON.stringify(tsconfig, undefined, 2));
    creating('tsconfig.json');
  } else {
    notCreating('tsconfig.json');
  }
  copyDirectory('@kui-shell/builder/examples/plugin-sample/package.json', 'plugins/plugin-sample', force);
  creating('reconfiguring package.json');
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const pjson = require((0, _path.join)(__dirname, '../../../../package.json'));
  pjson.main = 'node_modules/@kui-shell/core/dist/main/main.js';
  if (!pjson.devDependencies) {
    pjson.devDependencies = {};
  }
  pjson.devDependencies.mocha = '6.1.4';
  pjson.devDependencies['@types/mocha'] = '5.2.7';
  pjson.devDependencies['@types/node'] = '12.0.10';
  pjson.devDependencies.electron = '6.0.8';
  pjson.devDependencies.spectron = '8.0.0';
  pjson.devDependencies.typescript = '3.6.3';
  if (!pjson.dependencies) {
    pjson.dependencies = {};
  }
  pjson.dependencies['@kui-shell/plugin-sample'] = 'file:./plugins/plugin-sample';
  if (!pjson.scripts) {
    pjson.scripts = {};
  }
  pjson.scripts.init = 'if [ ! -e node_modules/@kui-shell/prescan.json ]; then kui-compile; fi';
  pjson.scripts.compile = 'kui-compile';
  pjson.scripts.watch = 'tsc --build . --watch';
  pjson.scripts['watch:webpack'] = 'kui-watch-webpack';
  pjson.scripts['pty:rebuild'] = 'cd node_modules/node-pty && npm run install';
  pjson.scripts['pty:electron'] = 'if [ ! -e node_modules/node-pty/.npmrc ]; then cp node_modules/@kui-shell/builder/npmrc node_modules/node-pty/.npmrc && npm run pty:rebuild; fi';
  pjson.scripts['pty:nodejs'] = 'if [ -e node_modules/node-pty/.npmrc ]; then rm -f node_modules/node-pty/.npmrc; npm run pty:rebuild; fi';
  pjson.scripts.start = 'npm run -s init && npm run -s pty:electron && electron . shell';
  yield (0, _fsExtra.writeFile)('package.json', JSON.stringify(pjson, undefined, 2));
  creating('npm install', 'running');
  yield new Promise((resolve, reject) => {
    (0, _child_process.exec)('npm install', (err, stdout, stderr) => {
      if (err) {
        console.error(err);
        reject(stderr);
      } else {
        resolve();
      }
    });
  });
});
exports.main = main;
main(process.argv);