/*****************************************************************************\
|                                               ( )_  _                       |
|    _ _    _ __   _ _    __    ___ ___     _ _ | ,_)(_)  ___   ___     _     |
|   ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| |  | |/',__)/' v `\ /'_`\   |
|   | (_) )| |  ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) )  |
|   | ,__/'(_)  `\__,_)`\__  |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/'  |
|   | |                ( )_) |                                                |
|   (_)                 \___/'                                                |
|                                                                             |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved.             |
| Licensed under the AGPL-3.0.                                                |
|                                                                             |
| According to our dual licensing model, this program can be used either      |
| under the terms of the GNU Affero General Public License, version 3,        |
| or under a proprietary license.                                             |
|                                                                             |
| The texts of the GNU Affero General Public License with an additional       |
| permission and of our proprietary license can be found at and               |
| in the LICENSE file you have received along with this program.              |
|                                                                             |
| This program is distributed in the hope that it will be useful,             |
| but WITHOUT ANY WARRANTY, without even the implied warranty of              |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                |
| GNU Affero General Public License for more details.                         |
|                                                                             |
| "General Bots" is a registered trademark of Pragmatismo.io.                 |
| The licensing of the program under the AGPLv3 does not imply a              |
| trademark license. Therefore any rights, title and interest in              |
| our trademarks remain entirely with us.                                     |
|                                                                             |
\*****************************************************************************/
/**
 * @fileoverview General Bots server core.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.GBServer = exports.RootData = void 0;
const express = require('express');
const bodyParser = require('body-parser');
const fs = require("fs");
const mkdirp = require('mkdirp');
const Path = require('path');
const botlib_1 = require("botlib");
const GBAdminService_1 = require("../packages/admin.gbapp/services/GBAdminService");
const AzureDeployerService_1 = require("../packages/azuredeployer.gbapp/services/AzureDeployerService");
const GBConfigService_1 = require("../packages/core.gbapp/services/GBConfigService");
const GBConversationalService_1 = require("../packages/core.gbapp/services/GBConversationalService");
const GBCoreService_1 = require("../packages/core.gbapp/services/GBCoreService");
const GBDeployer_1 = require("../packages/core.gbapp/services/GBDeployer");
const GBImporterService_1 = require("../packages/core.gbapp/services/GBImporterService");
const GBMinService_1 = require("../packages/core.gbapp/services/GBMinService");
/**
 * Global shared server data;
 */
class RootData {
}
exports.RootData = RootData;
/**
 * General Bots open-core entry point.
 */
class GBServer {
    /**
     *  Program entry-point.
     */
    static run() {
        botlib_1.GBLog.info(`The Bot Server is in STARTING mode...`);
        GBServer.globals = new RootData();
        GBConfigService_1.GBConfigService.init();
        const port = GBConfigService_1.GBConfigService.getServerPort();
        const server = express();
        GBServer.globals.server = server;
        GBServer.globals.appPackages = [];
        GBServer.globals.sysPackages = [];
        GBServer.globals.minInstances = [];
        GBServer.globals.wwwroot = null;
        GBServer.globals.entryPointDialog = null;
        server.use(bodyParser.json());
        server.use(bodyParser.urlencoded({ extended: true }));
        // Creates working directory.
        const workDir = Path.join(process.env.PWD, 'work');
        if (!fs.existsSync(workDir)) {
            mkdirp.sync(workDir);
        }
        server.listen(port, () => {
            (async () => {
                try {
                    botlib_1.GBLog.info(`Now accepting connections on ${port}...`);
                    // Reads basic configuration, initialize minimal services.
                    const core = new GBCoreService_1.GBCoreService();
                    const importer = new GBImporterService_1.GBImporter(core);
                    const deployer = new GBDeployer_1.GBDeployer(core, importer);
                    const azureDeployer = new AzureDeployerService_1.AzureDeployerService(deployer);
                    const adminService = new GBAdminService_1.GBAdminService(core);
                    if (process.env.NODE_ENV === 'development') {
                        const proxy = GBConfigService_1.GBConfigService.get('REVERSE_PROXY');
                        if (proxy !== undefined) {
                            GBServer.globals.publicAddress = proxy;
                        }
                        else {
                            // Ensure that local development proxy is setup.
                            botlib_1.GBLog.info(`Establishing a development local proxy (ngrok)...`);
                            GBServer.globals.publicAddress = await core.ensureProxy(port);
                        }
                        process.env.BOT_URL = GBServer.globals.publicAddress;
                    }
                    else {
                        const serverAddress = process.env.BOT_URL;
                        botlib_1.GBLog.info(`Defining server address at ${serverAddress}...`);
                        GBServer.globals.publicAddress = serverAddress;
                    }
                    // Creates a boot instance or load it from storage.
                    try {
                        await core.initStorage();
                    }
                    catch (error) {
                        botlib_1.GBLog.verbose(`Error initializing storage: ${error}`);
                        GBServer.globals.bootInstance =
                            await core.createBootInstance(core, azureDeployer, GBServer.globals.publicAddress);
                    }
                    core.ensureAdminIsSecured();
                    // Deploys system and user packages.
                    botlib_1.GBLog.info(`Deploying packages...`);
                    GBServer.globals.sysPackages = await core.loadSysPackages(core);
                    await core.checkStorage(azureDeployer);
                    await deployer.deployPackages(core, server, GBServer.globals.appPackages);
                    await core.syncDatabaseStructure();
                    botlib_1.GBLog.info(`Publishing instances...`);
                    const instances = await core.loadAllInstances(core, azureDeployer, GBServer.globals.publicAddress);
                    if (instances.length === 0) {
                        const instance = await importer.importIfNotExistsBotPackage(GBConfigService_1.GBConfigService.get('BOT_ID'), 'boot.gbot', 'packages/boot.gbot', GBServer.globals.bootInstance);
                        await deployer.deployBotFull(instance, GBServer.globals.publicAddress);
                        instances.push(instance);
                        await azureDeployer['runSearch'](instance);
                    }
                    GBServer.globals.bootInstance = instances[0];
                    // Builds minimal service infrastructure.
                    const conversationalService = new GBConversationalService_1.GBConversationalService(core);
                    const minService = new GBMinService_1.GBMinService(core, conversationalService, adminService, deployer);
                    GBServer.globals.minService = minService;
                    await minService.buildMin(instances);
                    // Deployment of local applications for the first time.
                    if (GBConfigService_1.GBConfigService.get('DISABLE_WEB') !== 'true') {
                        deployer.setupDefaultGBUI();
                    }
                    botlib_1.GBLog.info(`The Bot Server is in RUNNING mode...`);
                    // Opens Navigator.
                    // TODO: Config: core.openBrowserInDevelopment();
                }
                catch (err) {
                    botlib_1.GBLog.error(`STOP: ${err.message ? err.message : err} ${err.stack ? err.stack : ''}`);
                    process.exit(1);
                }
            })();
        });
    }
}
exports.GBServer = GBServer;
//# sourceMappingURL=app.js.map