#!/usr/bin/env node
"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 });
// npm link --force
// npm i npm install --global --production windows-build-tools
var fs = require("fs");
var Config_1 = require("./Config");
var cliutil_1 = require("./nodeclient/cliutil");
var openflow_api_1 = require("@openiap/openflow-api");
var pm2util_1 = require("./nodeclient/pm2util");
var optionDefinitions = [
    { name: 'verbose', alias: 'v', type: Boolean },
    { name: 'authenticate', alias: 'a', type: Boolean },
    { name: 'init', type: Boolean },
    { name: 'install', alias: 'i', type: Boolean },
    { name: 'uninstall', alias: 'u', type: Boolean },
    { name: 'start', type: Boolean },
    { name: 'restart', type: Boolean },
    { name: 'stop', type: Boolean },
    { name: 'run', type: Boolean },
    { name: 'name', type: String, defaultOption: true },
    { name: 'config', type: String },
    { name: 'inspect', type: String },
    { name: 'networks', type: Boolean }
];
var commandLineArgs = require('command-line-args');
var path = require('path');
var readlineSync = require('readline-sync');
var envfile = require('envfile');
var networkInterfaces = require('os').networkInterfaces;
var options = null;
try {
    options = commandLineArgs(optionDefinitions);
    if (!options.init) {
        if (options.networks) {
            var nets = networkInterfaces();
            for (var _i = 0, _a = Object.keys(nets); _i < _a.length; _i++) {
                var name_1 = _a[_i];
                for (var _b = 0, _c = nets[name_1]; _b < _c.length; _b++) {
                    var net = _c[_b];
                    // skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
                    if (net.family === 'IPv4' && !net.internal) {
                        //console.log(name, net);
                        console.log(name_1, net.address);
                    }
                }
            }
            process.exit();
        }
        if (options.name == null || options.name == "")
            throw new Error("Name is mandatory");
        if (options.name.endsWith(".env"))
            options.name = options.name.substring(0, options.name.length - 4);
        cliutil_1.servicename = options.name;
        cliutil_1.envfilename = options.name + ".env";
        cliutil_1.envfilepathname = path.join(process.cwd(), cliutil_1.envfilename);
        if (options.config != null && options.config != "")
            cliutil_1.envfilepathname = options.config;
        if (!cliutil_1.isOpenFlow()) {
            var parsedFile = envfile.parse(fs.readFileSync(cliutil_1.envfilepathname));
            if (parsedFile.jwt == null || parsedFile.jwt == "") {
                if (options.authenticate != true)
                    cliutil_1.logger.warn(cliutil_1.envfilename + " is missing a jwt, switching to --authenticate");
                options.authenticate = true;
            }
        }
    }
}
catch (error) {
    console.error(error.message ? error.message : error);
    printusage();
    process.exit();
}
function getToken() {
    var _this = this;
    return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
        var socket;
        var _this = this;
        return __generator(this, function (_a) {
            cliutil_1.logger.info("wsurl " + Config_1.Config.api_ws_url);
            socket = new openflow_api_1.WebSocketClient(cliutil_1.logger, Config_1.Config.api_ws_url);
            socket.agent = "nodered-cli";
            socket.version = Config_1.Config.version;
            socket.events.on("onopen", function () { return __awaiter(_this, void 0, void 0, function () {
                var username, password, result, error_1, closemsg;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            username = readlineSync.question('username? ');
                            password = readlineSync.question('password? ', { hideEchoBack: true });
                            return [4 /*yield*/, openflow_api_1.NoderedUtil.SigninWithUsername(username, password, null, true)];
                        case 1:
                            result = _a.sent();
                            cliutil_1.logger.info("signed in as " + result.user.name + " with id " + result.user._id);
                            openflow_api_1.WebSocketClient.instance.user = result.user;
                            openflow_api_1.WebSocketClient.instance.jwt = result.jwt;
                            socket.close(1000, "Close by user");
                            resolve(result.jwt);
                            socket = null;
                            return [3 /*break*/, 3];
                        case 2:
                            error_1 = _a.sent();
                            closemsg = (error_1.message ? error_1.message : error_1);
                            cliutil_1.logger.error(error_1);
                            socket.close(1000, closemsg);
                            reject(closemsg);
                            socket = null;
                            return [3 /*break*/, 3];
                        case 3: return [2 /*return*/];
                    }
                });
            }); });
            return [2 /*return*/];
        });
    }); });
}
function doit() {
    return __awaiter(this, void 0, void 0, function () {
        var files, i, filename, target, parsedFile, jwt, parsedFile, error_2, index, error_3;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 34, , 35]);
                    console.log("--- BEGIN!!!!");
                    if (!options.init) return [3 /*break*/, 1];
                    console.log("init");
                    files = fs.readdirSync(path.join(__dirname, ".."));
                    for (i = 0; i < files.length; i++) {
                        filename = files[i];
                        if (path.extname(filename) == '.env') {
                            target = path.join(process.cwd(), filename);
                            if (!fs.existsSync(target)) {
                                console.log("Creating " + filename);
                                filename = path.join(__dirname, "..", filename);
                                fs.copyFileSync(filename, target);
                                parsedFile = envfile.parse(fs.readFileSync(target));
                                parsedFile.logpath = process.cwd();
                                fs.writeFileSync(target, envfile.stringify(parsedFile));
                            }
                            else {
                                console.log("Skipping " + filename + " already exists.");
                            }
                        }
                    }
                    return [3 /*break*/, 33];
                case 1:
                    if (!(options.authenticate == true)) return [3 /*break*/, 11];
                    console.log("authenticate");
                    return [4 /*yield*/, pm2util_1.pm2exists(cliutil_1.servicename)];
                case 2:
                    if (!_a.sent()) return [3 /*break*/, 5];
                    return [4 /*yield*/, pm2util_1.pm2stop(cliutil_1.servicename)];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, pm2util_1.pm2delete(cliutil_1.servicename)];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    _a.trys.push([5, 9, , 10]);
                    cliutil_1.logger.info("isOpenFlow: " + cliutil_1.isOpenFlow());
                    if (!!cliutil_1.isOpenFlow()) return [3 /*break*/, 7];
                    cliutil_1.loadenv();
                    return [4 /*yield*/, getToken()];
                case 6:
                    jwt = _a.sent();
                    parsedFile = envfile.parse(fs.readFileSync(cliutil_1.envfilepathname));
                    parsedFile.jwt = jwt;
                    fs.writeFileSync(cliutil_1.envfilepathname, envfile.stringify(parsedFile));
                    openflow_api_1.WebSocketClient.instance.close(1000, "done");
                    _a.label = 7;
                case 7:
                    cliutil_1.loadenv();
                    return [4 /*yield*/, pm2util_1.pm2start({
                            name: cliutil_1.servicename,
                            script: __filename,
                            args: [cliutil_1.servicename, "--run", "--config", cliutil_1.envfilepathname]
                        })];
                case 8:
                    _a.sent();
                    cliutil_1.logger.info("Quit");
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 10];
                case 9:
                    error_2 = _a.sent();
                    cliutil_1.logger.error(error_2);
                    return [3 /*break*/, 10];
                case 10: return [3 /*break*/, 33];
                case 11:
                    if (!(options.install == true)) return [3 /*break*/, 20];
                    console.log("install");
                    cliutil_1.loadenv();
                    return [4 /*yield*/, pm2util_1.pm2exists(cliutil_1.servicename)];
                case 12:
                    if (!!(_a.sent())) return [3 /*break*/, 17];
                    return [4 /*yield*/, pm2util_1.pm2start({
                            name: cliutil_1.servicename,
                            script: __filename,
                            args: [cliutil_1.servicename, "--run", "--config", cliutil_1.envfilepathname]
                        })];
                case 13:
                    _a.sent();
                    if (!(process.platform != "win32")) return [3 /*break*/, 15];
                    return [4 /*yield*/, pm2util_1.pm2startup(process.platform)];
                case 14:
                    _a.sent();
                    _a.label = 15;
                case 15: return [4 /*yield*/, pm2util_1.pm2dump()];
                case 16:
                    _a.sent();
                    return [3 /*break*/, 19];
                case 17: return [4 /*yield*/, pm2util_1.pm2restart(cliutil_1.servicename)];
                case 18:
                    _a.sent();
                    _a.label = 19;
                case 19:
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 33];
                case 20:
                    if (!(options.uninstall == true)) return [3 /*break*/, 26];
                    console.log("uninstall");
                    return [4 /*yield*/, pm2util_1.pm2exists(cliutil_1.servicename)];
                case 21:
                    if (!_a.sent()) return [3 /*break*/, 24];
                    return [4 /*yield*/, pm2util_1.pm2stop(cliutil_1.servicename)];
                case 22:
                    _a.sent();
                    return [4 /*yield*/, pm2util_1.pm2delete(cliutil_1.servicename)];
                case 23:
                    _a.sent();
                    return [3 /*break*/, 25];
                case 24:
                    console.error(cliutil_1.servicename + " not found");
                    _a.label = 25;
                case 25:
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 33];
                case 26:
                    if (!(options.start == true)) return [3 /*break*/, 28];
                    console.log("start");
                    cliutil_1.loadenv();
                    return [4 /*yield*/, pm2util_1.pm2restart(cliutil_1.servicename)];
                case 27:
                    _a.sent();
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 33];
                case 28:
                    if (!(options.stop == true)) return [3 /*break*/, 30];
                    console.log("stop");
                    return [4 /*yield*/, pm2util_1.pm2stop(cliutil_1.servicename)];
                case 29:
                    _a.sent();
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 33];
                case 30:
                    if (!(options.restart == true)) return [3 /*break*/, 32];
                    console.log("restart");
                    return [4 /*yield*/, pm2util_1.pm2restart(cliutil_1.servicename)];
                case 31:
                    _a.sent();
                    pm2util_1.pm2disconnect();
                    return [3 /*break*/, 33];
                case 32:
                    if (options.run == true) {
                        pm2util_1.pm2disconnect();
                        console.log("run");
                        cliutil_1.loadenv();
                        cliutil_1.logger.info("Starting as service " + cliutil_1.servicename);
                        index = path.join(__dirname, "/index.js");
                        if (!fs.existsSync(index)) {
                            index = path.join(__dirname, "dist", "/index.js");
                        }
                        cliutil_1.logger.info("run: " + index);
                        require(index);
                    }
                    else {
                        console.log("unknown, print usage");
                        printusage();
                    }
                    _a.label = 33;
                case 33: return [3 /*break*/, 35];
                case 34:
                    error_3 = _a.sent();
                    console.error(error_3.message ? error_3.message : error_3);
                    process.exit();
                    return [3 /*break*/, 35];
                case 35: return [2 /*return*/];
            }
        });
    });
}
function printusage() {
    if (!cliutil_1.isOpenFlow()) {
        console.log("openflow-nodered-cli [--init][--install][--uninstall][--config][--start][--stop] name");
        console.log("   --init - Create sample environment files for running nodered");
        console.log("   --install - Install openflow as an service that runs at boot");
        console.log("   --uninstall - Uninstalls service, if openflow has been installed as an service");
        console.log("   --config - Prompt for credentials and create config");
        console.log("   --start - Will start the service with the given name");
        console.log("   --stop - Will stop the service with the given name");
        console.log("   name - Service and instance name");
        console.log("Will look for an envoriment file called name.env and copy that to the");
        console.log("source directory");
        return;
    }
    console.log("openflow-cli [--init][--install][--uninstall][--start][--stop] name");
    console.log("   --init - Create a sample environment file for running openflow");
    console.log("   --install - Install openflow as an service that runs at boot");
    console.log("   --uninstall - Uninstalls service, if openflow has been installed as an service");
    console.log("   --start - Will start the service with the given name");
    console.log("   --stop - Will stop the service with the given name");
    console.log("   name - Service and instance name");
    console.log("Will look for an envoriment file called name.env and copy that to the");
    console.log("source directory");
}
doit();
// node C:\code\openflow\OpenFlowNodeRED\dist\cli.js --install noderedlocal
//# sourceMappingURL=cli.js.map