"use strict";
var __awaiter = (this && this.__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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var Logger_1 = require("./Logger");
var WebServer_1 = require("./WebServer");
var WebSocketServer_1 = require("./WebSocketServer");
var DatabaseConnection_1 = require("./DatabaseConnection");
var Crypt_1 = require("./Crypt");
var Config_1 = require("./Config");
var amqpwrapper_1 = require("./amqpwrapper");
var openflow_api_1 = require("@openiap/openflow-api");
var DBHelper_1 = require("./DBHelper");
var OAuthProvider_1 = require("./OAuthProvider");
Logger_1.Logger.configure();
var _lic_require = null;
try {
    _lic_require = require("./license-file");
}
catch (error) {
}
if (_lic_require != null) {
    Logger_1.Logger.License = new _lic_require.LicenseFile();
}
else {
    Logger_1.Logger.License = {};
    Logger_1.Logger.License.ofid = function () {
        if (!openflow_api_1.NoderedUtil.IsNullEmpty(this._ofid))
            return this._ofid;
        var crypto = require('crypto');
        var openflow_uniqueid = Config_1.Config.openflow_uniqueid || crypto.createHash('md5').update(Config_1.Config.domain).digest("hex");
        Config_1.Config.openflow_uniqueid = openflow_uniqueid;
        this._ofid = openflow_uniqueid;
        return openflow_uniqueid;
    };
}
var _otel_require = null;
try {
    _otel_require = require("./otel");
}
catch (error) {
}
if (_otel_require != null) {
    Logger_1.Logger.otel = _otel_require.otel.configure();
}
else {
    var fakespan_1 = {
        context: function () { return undefined; },
        setAttribute: function () { return undefined; },
        setAttributes: function () { return undefined; },
        addEvent: function () { return undefined; },
        setStatus: function () { return undefined; },
        updateName: function () { return undefined; },
        end: function () { return undefined; },
        isRecording: function () { return undefined; },
        recordException: function () { return undefined; },
    };
    Logger_1.Logger.otel =
        {
            startSpan: function () { return fakespan_1; },
            startSubSpan: function () { return fakespan_1; },
            endSpan: function () { return undefined; },
            startTimer: function () { return undefined; },
            endTimer: function () { return undefined; },
            setdefaultlabels: function () { return undefined; },
            meter: {
                createValueRecorder: function () { return undefined; },
                createCounter: function () { return undefined; },
                createUpDownSumObserver: function () { return undefined; },
            }
        };
}
Config_1.Config.db = new DatabaseConnection_1.DatabaseConnection(Config_1.Config.mongodb_url, Config_1.Config.mongodb_db);
function initamqp() {
    return __awaiter(this, void 0, void 0, function () {
        var amqp;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    amqp = new amqpwrapper_1.amqpwrapper(Config_1.Config.amqp_url);
                    amqpwrapper_1.amqpwrapper.SetInstance(amqp);
                    return [4 /*yield*/, amqp.connect()];
                case 1:
                    _a.sent();
                    // Must also consume messages in the dead letter queue, to catch messages that have timed out
                    return [4 /*yield*/, amqp.AddExchangeConsumer(Config_1.Config.amqp_dlx, "fanout", "", null, null, function (msg, options, ack, done) { return __awaiter(_this, void 0, void 0, function () {
                            var error_1;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (typeof msg === "string" || msg instanceof String) {
                                            try {
                                                msg = JSON.parse(msg);
                                            }
                                            catch (error) {
                                            }
                                        }
                                        _a.label = 1;
                                    case 1:
                                        _a.trys.push([1, 3, , 4]);
                                        msg.command = "timeout";
                                        // Resend message, this time to the reply queue for the correct node (replyTo)
                                        // this.SendMessage(JSON.stringify(data), msg.properties.replyTo, msg.properties.correlationId, false);
                                        Logger_1.Logger.instanse.info("[DLX][" + options.exchange + "] Send timeout to " + options.replyTo);
                                        return [4 /*yield*/, amqpwrapper_1.amqpwrapper.Instance().sendWithReply("", options.replyTo, msg, 20000, options.correlationId)];
                                    case 2:
                                        _a.sent();
                                        return [3 /*break*/, 4];
                                    case 3:
                                        error_1 = _a.sent();
                                        console.error("Failed sending deadletter message to " + options.replyTo);
                                        console.error(error_1);
                                        return [3 /*break*/, 4];
                                    case 4:
                                        ack();
                                        done();
                                        return [2 /*return*/];
                                }
                            });
                        }); }, undefined)];
                case 2:
                    // Must also consume messages in the dead letter queue, to catch messages that have timed out
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
// let flipper: boolean = false;
// async function doitagain() {
//     try {
//         flipper = !flipper;
//         if (flipper) {
//             console.info(await amqpwrapper.Instance().sendWithReply("", "testqueue", "Hi mom", 20000, ""));
//         } else {
//             // console.info(await amqpwrapper.Instance().sendWithReply("", "testqueue2", "Hi mom", 2000));
//             console.info(await amqpwrapper.Instance().sendWithReply("testexchange", "", "Hi mom", 20000, ""));
//         }
//     } catch (error) {
//         console.error(error);
//     }
//     setTimeout(() => {
//         doitagain()
//     }, 5000);
// }
function initDatabase() {
    return __awaiter(this, void 0, void 0, function () {
        var span, jwt, admins, users, root, robot_agent_users, personal_nodered_users, nodered_admins, nodered_users, nodered_api_users, robot_admins, robot_users, filestore_admins, filestore_users, error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    span = Logger_1.Logger.otel.startSpan("initDatabase");
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 29, , 30]);
                    jwt = Crypt_1.Crypt.rootToken();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "admins", openflow_api_1.WellknownIds.admins, span)];
                case 2:
                    admins = _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "users", openflow_api_1.WellknownIds.users, span)];
                case 3:
                    users = _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.ensureUser(jwt, "root", "root", openflow_api_1.WellknownIds.root, null, span)];
                case 4:
                    root = _a.sent();
                    openflow_api_1.Base.addRight(root, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(root, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    openflow_api_1.Base.addRight(root, openflow_api_1.WellknownIds.root, "root", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(root, openflow_api_1.WellknownIds.root, [openflow_api_1.Rights.delete]);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(root, jwt, span)];
                case 5:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot agent users", openflow_api_1.WellknownIds.robot_agent_users, span)];
                case 6:
                    robot_agent_users = _a.sent();
                    openflow_api_1.Base.addRight(robot_agent_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(robot_agent_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    openflow_api_1.Base.addRight(robot_agent_users, openflow_api_1.WellknownIds.root, "root", [openflow_api_1.Rights.full_control]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + robot_agent_users.name + " from self");
                        openflow_api_1.Base.removeRight(robot_agent_users, robot_agent_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(robot_agent_users, robot_agent_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(robot_agent_users, robot_agent_users._id, "robot agent users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(robot_agent_users, jwt, span)];
                case 7:
                    _a.sent();
                    openflow_api_1.Base.addRight(admins, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(admins, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(admins, jwt, span)];
                case 8:
                    _a.sent();
                    openflow_api_1.Base.addRight(users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    users.AddMember(root);
                    if (Config_1.Config.multi_tenant) {
                        openflow_api_1.Base.removeRight(users, users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else {
                        openflow_api_1.Base.removeRight(users, users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(users, users._id, "users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(users, jwt, span)];
                case 9:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "personal nodered users", openflow_api_1.WellknownIds.personal_nodered_users, span)];
                case 10:
                    personal_nodered_users = _a.sent();
                    personal_nodered_users.AddMember(admins);
                    openflow_api_1.Base.addRight(personal_nodered_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(personal_nodered_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + personal_nodered_users.name + " from self");
                        openflow_api_1.Base.removeRight(personal_nodered_users, personal_nodered_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(personal_nodered_users, personal_nodered_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(personal_nodered_users, personal_nodered_users._id, "personal nodered users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(personal_nodered_users, jwt, span)];
                case 11:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered admins", openflow_api_1.WellknownIds.nodered_admins, span)];
                case 12:
                    nodered_admins = _a.sent();
                    nodered_admins.AddMember(admins);
                    openflow_api_1.Base.addRight(nodered_admins, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(nodered_admins, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(nodered_admins, jwt, span)];
                case 13:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered users", openflow_api_1.WellknownIds.nodered_users, span)];
                case 14:
                    nodered_users = _a.sent();
                    nodered_users.AddMember(admins);
                    openflow_api_1.Base.addRight(nodered_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(nodered_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + nodered_users.name + " from self");
                        openflow_api_1.Base.removeRight(nodered_users, nodered_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(nodered_users, nodered_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(nodered_users, nodered_users._id, "nodered users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(nodered_users, jwt, span)];
                case 15:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered api users", openflow_api_1.WellknownIds.nodered_api_users, span)];
                case 16:
                    nodered_api_users = _a.sent();
                    nodered_api_users.AddMember(admins);
                    openflow_api_1.Base.addRight(nodered_api_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(nodered_api_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + nodered_api_users.name + " from self");
                        openflow_api_1.Base.removeRight(nodered_api_users, nodered_api_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(nodered_api_users, nodered_api_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(nodered_api_users, nodered_api_users._id, "nodered api users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(nodered_api_users, jwt, span)];
                case 17:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot admins", openflow_api_1.WellknownIds.robot_admins, span)];
                case 18:
                    robot_admins = _a.sent();
                    robot_admins.AddMember(admins);
                    openflow_api_1.Base.addRight(robot_admins, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(robot_admins, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(robot_admins, jwt, span)];
                case 19:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot users", openflow_api_1.WellknownIds.robot_users, span)];
                case 20:
                    robot_users = _a.sent();
                    robot_users.AddMember(admins);
                    robot_users.AddMember(users);
                    openflow_api_1.Base.addRight(robot_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(robot_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + robot_users.name + " from self");
                        openflow_api_1.Base.removeRight(robot_users, robot_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(robot_users, robot_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(robot_users, robot_users._id, "robot users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(robot_users, jwt, span)];
                case 21:
                    _a.sent();
                    if (!!admins.IsMember(root._id)) return [3 /*break*/, 23];
                    admins.AddMember(root);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(admins, jwt, span)];
                case 22:
                    _a.sent();
                    _a.label = 23;
                case 23: return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "filestore admins", openflow_api_1.WellknownIds.filestore_admins, span)];
                case 24:
                    filestore_admins = _a.sent();
                    filestore_admins.AddMember(admins);
                    openflow_api_1.Base.addRight(filestore_admins, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(filestore_admins, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + filestore_admins.name + " from self");
                        openflow_api_1.Base.removeRight(filestore_admins, filestore_admins._id, [openflow_api_1.Rights.full_control]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(filestore_admins, jwt, span)];
                case 25:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "filestore users", openflow_api_1.WellknownIds.filestore_users, span)];
                case 26:
                    filestore_users = _a.sent();
                    filestore_users.AddMember(admins);
                    if (!Config_1.Config.multi_tenant) {
                        filestore_users.AddMember(users);
                    }
                    openflow_api_1.Base.addRight(filestore_users, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                    openflow_api_1.Base.removeRight(filestore_users, openflow_api_1.WellknownIds.admins, [openflow_api_1.Rights.delete]);
                    if (Config_1.Config.multi_tenant) {
                        Logger_1.Logger.instanse.debug("[root][users] Running in multi tenant mode, remove " + filestore_users.name + " from self");
                        openflow_api_1.Base.removeRight(filestore_users, filestore_users._id, [openflow_api_1.Rights.full_control]);
                    }
                    else if (Config_1.Config.update_acl_based_on_groups) {
                        openflow_api_1.Base.removeRight(filestore_users, filestore_users._id, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(filestore_users, filestore_users._id, "filestore users", [openflow_api_1.Rights.read]);
                    }
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(filestore_users, jwt, span)];
                case 27:
                    _a.sent();
                    return [4 /*yield*/, Config_1.Config.db.ensureindexes(span)];
                case 28:
                    _a.sent();
                    Logger_1.Logger.otel.endSpan(span);
                    return [2 /*return*/, true];
                case 29:
                    error_2 = _a.sent();
                    span.recordException(error_2);
                    Logger_1.Logger.otel.endSpan(span);
                    Logger_1.Logger.instanse.error(error_2);
                    return [2 /*return*/, false];
                case 30: return [2 /*return*/];
            }
        });
    });
}
process.on('beforeExit', function (code) {
    console.error('Process beforeExit event with code: ', code);
});
process.on('exit', function (code) {
    console.error('Process exit event with code: ', code);
});
process.on('multipleResolves', function (type, promise, reason) {
    // console.error(type, promise, reason);
    // setImmediate(() => process.exit(1));
});
var unhandledRejections = new Map();
process.on('unhandledRejection', function (reason, promise) {
    console.error('Unhandled Rejection at: Promise', promise, 'reason:', reason);
    unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', function (promise) {
    unhandledRejections.delete(promise);
});
process.on('uncaughtException', function (err, origin) {
    console.error("Caught exception: " + err + "\n" +
        ("Exception origin: " + origin));
});
process.on('uncaughtExceptionMonitor', function (err, origin) {
    console.error("Caught exception Monitor: " + err + "\n" +
        ("Exception origin: " + origin));
});
process.on('warning', function (warning) {
    try {
        console.warn(warning.name + ": " + warning.message);
        console.warn(warning.stack);
    }
    catch (error) {
    }
});
// The signals we want to handle
// NOTE: although it is tempting, the SIGKILL signal (9) cannot be intercepted and handled
var signals = {
    'SIGHUP': 1,
    'SIGINT': 2,
    'SIGTERM': 15
};
function handle(signal, value) {
    console.trace("process received a " + signal + " signal with value " + value);
    try {
        server.close(function (err) {
            console.log("server stopped by " + signal + " with value " + value);
            console.error(err);
            process.exit(128 + value);
        });
    }
    catch (error) {
        console.error(error);
        console.log("server stopped by " + signal + " with value " + value);
        process.exit(128 + value);
    }
}
Object.keys(signals).forEach(function (signal) { return process.on(signal, handle); });
// process.on('SIGTERM', handle);
// process.on('SIGINT', handle);
// process.on('SIGUSR1', handle);
// process.on('SIGPIPE', handle);
// process.on('SIGHUP', handle);
// process.on('SIGBREAK', handle);
// process.on('SIGKILL', handle);
// process.on('SIGWINCH', handle);
// process.on('SIGSTOP', handle);
// process.on('SIGBUS', handle);
// process.on('SIGFPE', handle);
// process.on('SIGSEGV', handle);
// process.on('SIGILL', handle);
var GrafanaProxy = null;
try {
    GrafanaProxy = require("./grafana-proxy");
}
catch (error) {
}
var Prometheus = null;
try {
    Prometheus = require("./Prometheus");
}
catch (error) {
}
var originalStdoutWrite = process.stdout.write.bind(process.stdout);
var originalStderrWrite = process.stderr.write.bind(process.stderr);
process.stdout.write = function (chunk, encoding, callback) {
    return originalStdoutWrite(chunk, encoding, callback);
};
process.stderr.write = function (chunk, encoding, callback) {
    return originalStderrWrite(chunk, encoding, callback);
};
// write(buffer: Buffer | Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
// write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean;
// https://medium.com/kubernetes-tutorials/monitoring-your-kubernetes-deployments-with-prometheus-5665eda54045
var server = null;
(function () {
    return __awaiter(this, void 0, void 0, function () {
        var grafana, error_3;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 6, , 7]);
                    return [4 /*yield*/, initamqp()];
                case 1:
                    _a.sent();
                    Logger_1.Logger.instanse.info("VERSION: " + Config_1.Config.version);
                    return [4 /*yield*/, WebServer_1.WebServer.configure(Config_1.Config.baseurl())];
                case 2:
                    server = _a.sent();
                    if (!(GrafanaProxy != null)) return [3 /*break*/, 4];
                    return [4 /*yield*/, GrafanaProxy.GrafanaProxy.configure(WebServer_1.WebServer.app)];
                case 3:
                    grafana = _a.sent();
                    _a.label = 4;
                case 4:
                    OAuthProvider_1.OAuthProvider.configure(WebServer_1.WebServer.app);
                    WebSocketServer_1.WebSocketServer.configure(server);
                    Logger_1.Logger.instanse.info("listening on " + Config_1.Config.baseurl());
                    Logger_1.Logger.instanse.info("namespace: " + Config_1.Config.namespace);
                    return [4 /*yield*/, initDatabase()];
                case 5:
                    if (!(_a.sent())) {
                        process.exit(404);
                    }
                    return [3 /*break*/, 7];
                case 6:
                    error_3 = _a.sent();
                    Logger_1.Logger.instanse.error(error_3);
                    process.exit(404);
                    return [3 /*break*/, 7];
                case 7: return [2 /*return*/];
            }
        });
    });
})();
//# sourceMappingURL=index.js.map