'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var chalk = require('chalk');
var inquirer = require('inquirer');
var path = require('path');
var cliCommon = require('@backstage/cli-common');
var os = require('os');
var fs = require('fs-extra');
var tasks = require('./lib/tasks.cjs.js');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

var chalk__default = /*#__PURE__*/_interopDefaultCompat(chalk);
var inquirer__default = /*#__PURE__*/_interopDefaultCompat(inquirer);
var os__default = /*#__PURE__*/_interopDefaultCompat(os);
var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);

const DEFAULT_BRANCH = "master";
var createApp = async (opts) => {
  const paths = cliCommon.findPaths(__dirname);
  const answers = await inquirer__default.default.prompt([
    {
      type: "input",
      name: "name",
      default: "backstage",
      message: chalk__default.default.blue("Enter a name for the app [required]"),
      validate: (value) => {
        if (!value) {
          return chalk__default.default.red("Please enter a name for the app");
        } else if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(value)) {
          return chalk__default.default.red(
            "App name must be lowercase and contain only letters, digits, and dashes."
          );
        }
        return true;
      },
      when: (a) => {
        const envName = process.env.BACKSTAGE_APP_NAME;
        if (envName) {
          a.name = envName;
          return false;
        }
        return true;
      }
    }
  ]);
  const templateDir = opts.templatePath ? paths.resolveTarget(opts.templatePath) : paths.resolveOwn("templates/default-app");
  const appDir = opts.path ? path.resolve(paths.targetDir, opts.path) : path.resolve(paths.targetDir, answers.name);
  tasks.Task.log();
  tasks.Task.log("Creating the app...");
  try {
    const gitConfig = await tasks.readGitConfig();
    if (opts.path) {
      tasks.Task.section("Checking that supplied path exists");
      await tasks.checkPathExistsTask(appDir);
      tasks.Task.section("Preparing files");
      await tasks.templatingTask(templateDir, opts.path, {
        ...answers,
        defaultBranch: gitConfig?.defaultBranch ?? DEFAULT_BRANCH
      });
    } else {
      tasks.Task.section("Checking if the directory is available");
      await tasks.checkAppExistsTask(paths.targetDir, answers.name);
      tasks.Task.section("Creating a temporary app directory");
      const tempDir = await fs__default.default.mkdtemp(path.resolve(os__default.default.tmpdir(), answers.name));
      tasks.Task.section("Preparing files");
      await tasks.templatingTask(templateDir, tempDir, {
        ...answers,
        defaultBranch: gitConfig?.defaultBranch ?? DEFAULT_BRANCH
      });
      tasks.Task.section("Moving to final location");
      await tasks.moveAppTask(tempDir, appDir, answers.name);
    }
    const fetchedYarnLockSeed = await tasks.fetchYarnLockSeedTask(appDir);
    if (gitConfig) {
      if (await tasks.tryInitGitRepository(appDir)) {
        tasks.Task.forItem("init", "git repository", async () => {
        });
      }
    }
    if (!opts.skipInstall) {
      tasks.Task.section("Installing dependencies");
      await tasks.buildAppTask(appDir);
    }
    tasks.Task.log();
    tasks.Task.log(
      chalk__default.default.green(`\u{1F947}  Successfully created ${chalk__default.default.cyan(answers.name)}`)
    );
    tasks.Task.log();
    if (!fetchedYarnLockSeed) {
      tasks.Task.log(
        chalk__default.default.yellow(
          [
            "Warning: Failed to fetch the yarn.lock seed file.",
            "         You may end up with incompatible dependencies that break the app.",
            "         If you run into any errors, please search the issues at",
            "         https://github.com/backstage/backstage/issues for potential solutions"
          ].join("\n")
        )
      );
    }
    tasks.Task.section("All set! Now you might want to");
    if (opts.skipInstall) {
      tasks.Task.log(
        `  Install the dependencies: ${chalk__default.default.cyan(
          `cd ${opts.path ?? answers.name} && yarn install`
        )}`
      );
    }
    tasks.Task.log(
      `  Run the app: ${chalk__default.default.cyan(
        `cd ${opts.path ?? answers.name} && yarn dev`
      )}`
    );
    tasks.Task.log(
      "  Set up the software catalog: https://backstage.io/docs/features/software-catalog/configuration"
    );
    tasks.Task.log("  Add authentication: https://backstage.io/docs/auth/");
    tasks.Task.log();
    tasks.Task.exit();
  } catch (error) {
    tasks.Task.error(String(error));
    tasks.Task.log("It seems that something went wrong when creating the app \u{1F914}");
    tasks.Task.error("\u{1F525}  Failed to create app!");
    tasks.Task.exit(1);
  }
};

exports.default = createApp;
//# sourceMappingURL=createApp.cjs.js.map
