"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 logger = Logger_1.Logger.configure();
Config_1.Config.db = new DatabaseConnection_1.DatabaseConnection(logger, Config_1.Config.mongodb_url, Config_1.Config.mongodb_db);
function initamqp() {
    return __awaiter(this, void 0, void 0, function () {
        var amqp;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    amqp = new amqpwrapper_1.amqpwrapper(logger, 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) {
                            if (typeof msg === "string" || msg instanceof String) {
                                try {
                                    msg = JSON.parse(msg);
                                }
                                catch (error) {
                                }
                            }
                            try {
                                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);
                                console.log("[DLX][" + options.exchange + "] Send timeout to " + options.replyTo);
                                amqpwrapper_1.amqpwrapper.Instance().sendWithReply("", options.replyTo, msg, 20000, options.correlationId);
                            }
                            catch (error) {
                            }
                            ack();
                            done();
                        })];
                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.log(await amqpwrapper.Instance().sendWithReply("", "testqueue", "Hi mom", 20000, ""));
//         } else {
//             // console.log(await amqpwrapper.Instance().sendWithReply("", "testqueue2", "Hi mom", 2000));
//             console.log(await amqpwrapper.Instance().sendWithReply("testexchange", "", "Hi mom", 20000, ""));
//         }
//     } catch (error) {
//         console.log(error);
//     }
//     setTimeout(() => {
//         doitagain()
//     }, 5000);
// }
function initDatabase() {
    return __awaiter(this, void 0, void 0, function () {
        var 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_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 27, , 28]);
                    jwt = Crypt_1.Crypt.rootToken();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "admins", openflow_api_1.WellknownIds.admins)];
                case 1:
                    admins = _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "users", openflow_api_1.WellknownIds.users)];
                case 2:
                    users = _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.ensureUser(jwt, "root", "root", openflow_api_1.WellknownIds.root, null)];
                case 3:
                    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)];
                case 4:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot agent users", openflow_api_1.WellknownIds.robot_agent_users)];
                case 5:
                    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.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)];
                case 6:
                    _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)];
                case 7:
                    _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)];
                case 8:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "personal nodered users", openflow_api_1.WellknownIds.personal_nodered_users)];
                case 9:
                    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.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)];
                case 10:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered admins", openflow_api_1.WellknownIds.nodered_admins)];
                case 11:
                    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)];
                case 12:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered users", openflow_api_1.WellknownIds.nodered_users)];
                case 13:
                    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.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)];
                case 14:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "nodered api users", openflow_api_1.WellknownIds.nodered_api_users)];
                case 15:
                    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.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)];
                case 16:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot admins", openflow_api_1.WellknownIds.robot_admins)];
                case 17:
                    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)];
                case 18:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "robot users", openflow_api_1.WellknownIds.robot_users)];
                case 19:
                    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.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)];
                case 20:
                    _a.sent();
                    if (!!admins.IsMember(root._id)) return [3 /*break*/, 22];
                    admins.AddMember(root);
                    return [4 /*yield*/, DBHelper_1.DBHelper.Save(admins, jwt)];
                case 21:
                    _a.sent();
                    _a.label = 22;
                case 22: return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "filestore admins", openflow_api_1.WellknownIds.filestore_admins)];
                case 23:
                    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.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)];
                case 24:
                    _a.sent();
                    return [4 /*yield*/, DBHelper_1.DBHelper.EnsureRole(jwt, "filestore users", openflow_api_1.WellknownIds.filestore_users)];
                case 25:
                    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.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)];
                case 26:
                    _a.sent();
                    return [2 /*return*/, true];
                case 27:
                    error_1 = _a.sent();
                    logger.error(error_1);
                    return [2 /*return*/, false];
                case 28: return [2 /*return*/];
            }
        });
    });
}
var unhandledRejection = require("unhandled-rejection");
var rejectionEmitter = unhandledRejection({
    timeout: 20
});
rejectionEmitter.on("unhandledRejection", function (error, promise) {
    console.log('Unhandled Rejection at: Promise', promise, 'reason:', error);
    console.dir(error.stack);
});
rejectionEmitter.on("rejectionHandled", function (error, promise) {
    console.log('Rejection handled at: Promise', promise, 'reason:', error);
    console.dir(error.stack);
});
var OAuthProvider_1 = require("./OAuthProvider");
var GrafanaProxy = null;
try {
    GrafanaProxy = require("./grafana-proxy");
}
catch (error) {
}
var Prometheus = null;
var register = 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) {
    if (chunk.indexOf("Failed locating user with") > -1) {
        console.log("bump");
    }
    return originalStdoutWrite(chunk, encoding, callback);
};
process.stderr.write = function (chunk, encoding, callback) {
    if (chunk.indexOf("Failed locating user with") > -1) {
        console.log("bump");
    }
    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
(function () {
    return __awaiter(this, void 0, void 0, function () {
        var server, grafana, error_2;
        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.info("VERSION: " + Config_1.Config.version);
                    if (Prometheus != null) {
                        register = Prometheus.Prometheus.configure(logger);
                    }
                    return [4 /*yield*/, WebServer_1.WebServer.configure(logger, Config_1.Config.baseurl(), register)];
                case 2:
                    server = _a.sent();
                    if (!(GrafanaProxy != null)) return [3 /*break*/, 4];
                    return [4 /*yield*/, GrafanaProxy.GrafanaProxy.configure(logger, WebServer_1.WebServer.app, register)];
                case 3:
                    grafana = _a.sent();
                    _a.label = 4;
                case 4:
                    OAuthProvider_1.OAuthProvider.configure(logger, WebServer_1.WebServer.app);
                    WebSocketServer_1.WebSocketServer.configure(logger, server, register);
                    logger.info("listening on " + Config_1.Config.baseurl());
                    logger.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_2 = _a.sent();
                    logger.error(error_2);
                    process.exit(404);
                    return [3 /*break*/, 7];
                case 7: return [2 /*return*/];
            }
        });
    });
})();
//# sourceMappingURL=index.js.map