"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const child_process_1 = require("child_process");
const nodeUtil = require("util");
const ops_1 = require("../ops");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
const cli_common_1 = require("../cli-common");
const command_base_tenantless_1 = require("../command-base-tenantless");
const execAsync = nodeUtil.promisify(child_process_1.exec); // antiquated nastiness
class Run extends command_base_tenantless_1.CommandBaseTenantless {
    logOutput(output) {
        this.logger.debug(this._styler.dim(output.stderr) + this._styler.dim(output.stdout));
    }
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                return this.exec.runWithDefaults(yield this.parse(Run), (args, flags) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                    return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
                        try {
                            // -------------------------------------------------
                            // TODO:  Retrieve image specs from the ImageExport
                            // -------------------------------------------------
                            let imageExport = {};
                            if (this._projCfg.images) {
                                for (let key in this._projCfg.images) {
                                    imageExport = this._projCfg.images[key];
                                    break;
                                }
                            }
                            let version = (_a = imageExport.version) !== null && _a !== void 0 ? _a : yield this._ops.getCodeVersion();
                            let image = `${imageExport.name}:${version}`; // `${this._projCfg.name}:${version}`;
                            let containerName = `${this._projCfg.name}`; // TODO:  Add tenantCode as scope for the container.
                            if (flags.build) {
                                this._ui.startSpinner(`Building...`);
                                yield this.build();
                                this._ui.stopSpinner("complete.");
                            }
                            let detach = (flags.detach || flags.watch) ? " -d" : "";
                            let entryPoint = (flags.entrypoint) ? ` ${flags.entrypoint}` : "";
                            // Fall back on EXPOSE cmd in the image, available via '$ docker image inspect'
                            // https://docs.docker.com/engine/reference/builder/#expose
                            let extPort = (flags.port) ? flags.port : ops_1.DxConstants.DEFAULT_EXTERNAL_PORT;
                            // DETERMINE INTERNAL PORT
                            let tsconfig = this._ops.readTsConfig();
                            let outdir = (tsconfig) ? tsconfig.compilerOptions.outDir : undefined || ops_1.DxConstants.DEFAULT_BUILD_OUTPUT_DIR;
                            let config = this._ops.loadConfig(outdir);
                            let intPort;
                            if (flags.internalPort) {
                                intPort = flags.internalPort;
                            }
                            else {
                                intPort = (config ? config["port"] || config["portLastUsed"] : undefined) || ops_1.DxConstants.DEFAULT_INTERNAL_PORT;
                            }
                            this.logger.debug(`Internal port: ${this._styler.hilite("" + intPort)}`);
                            let intx = (flags.interactive && !flags.watch) ? " -it" : "";
                            let nwk = (flags.network) ? flags.network : this._projCfg.tenantCode;
                            let cliExec = new codiac_ops_common_1.CliExec(this.logger);
                            // let nid = await execAsync(`docker network ls -f name=${nwk} -q`);  // CANT use this!  Does a "name contains" not "name equals"
                            // Here's Docker forcing us to do an existence-by-exception check;
                            // I just hope that exception is in fact a non existence fail,
                            // and not a valid exception thrown for another reason.
                            // Oh well, guess this is acceptable engineering in their world...
                            try {
                                let nid = yield cliExec.execAsyncStdOut(`docker network inspect ${nwk} -f "{{.Id}}"`, { cwd: this._projectRoot });
                            }
                            catch (err) {
                                let cmd = `docker network create ${nwk} --driver bridge`;
                                this.logger.detail(`Creating docker network: ${nwk}...`);
                                let responseCode = yield cliExec.spawnAndLog(cmd, this._projectRoot);
                            }
                            this.logger.detail(`Attaching to the following Docker network [name=${nwk}]...`);
                            cliExec.spawnAndLog(`docker network ls -f name=${nwk}`, this._projectRoot);
                            // let showNetwork = await execAsync(`docker network ls -f name=${nwk}`);
                            // Run.logOutput(showNetwork);
                            // TODO: Give the user the ability to get the container info:  exposed ports, network name, image name
                            // remove any existing
                            let existing = yield execAsync(`docker ps -a -f name=${containerName} -q`);
                            if (existing.stdout) {
                                this.logger.detail(`removing previously existing container...`);
                                let rm = yield execAsync(`docker rm -f ${containerName}`);
                                this.logOutput(rm);
                            }
                            let dockerflags = {};
                            let dockerArgs = [];
                            dockerflags["--name"] = containerName;
                            dockerflags["--expose"] = `${extPort}`;
                            dockerflags["-p"] = `${extPort}:${intPort}`;
                            dockerflags["-e"] = `LISTEN_ON=${intPort}`;
                            dockerflags["--network"] = `${nwk}${intx}${detach}`;
                            if (flags.mountFolder !== undefined) {
                                let parts = flags.mountFolder.split(",");
                                if (parts.length === 2) {
                                    let src = parts[0].split("=");
                                    if (src.length === 2) {
                                        let srcPath = codiac_ops_common_1.OpsUtils.resolveHomeDir(src[1]);
                                        let dst = parts[1].split("=");
                                        if (dst.length === 2) {
                                            // let dstPath = resolveHomeDir(parts[1].split("=")[1]);
                                            let dstPath = dst[1];
                                            dockerflags["--mount"] = `type=bind,src=${srcPath},dst=${dstPath}`;
                                        }
                                    }
                                }
                                if (!dockerflags["--mount"]) {
                                    this.logger.debug(`Incorrect format for --mountFolder; use "src=~/my/local/folder,dst=/root/in/container"`);
                                }
                            }
                            dockerArgs.push(image);
                            if (entryPoint !== undefined && entryPoint !== "")
                                dockerArgs.push(entryPoint);
                            let dockerCmd = "docker run";
                            for (let flag in dockerflags) {
                                dockerCmd = dockerCmd.concat(" ", flag, " ", dockerflags[flag]);
                            }
                            for (let arg of dockerArgs) {
                                dockerCmd = dockerCmd.concat(" ", arg);
                            }
                            // let dockerCmd = `docker run --name ${containerName} --expose ${extPort} -p ${extPort}:${intPort} -e LISTEN_ON=${intPort} --network ${nwk}${intx}${detach} ${image} ${entryPoint}`;
                            this.logger.detail(`Running the container: ${image} as ${this._styler.hilite(containerName)}`);
                            this.logger.debug(dockerCmd);
                            // let publicUrl = `http://localhost:${extPort}/openApi`
                            let publicUrl = `http://localhost:${extPort}/`;
                            if (flags.watch) {
                                // Run the container (watching forces detach, so we know this command will start and release)
                                let runOutput = yield execAsync(dockerCmd);
                                this.logOutput(runOutput);
                                this._ui.userMessage(this._styler.colorGood(`${this._styler.hilite(image)} is now available at ${this._styler.hilite(publicUrl)}`));
                                // Stream the "docker logs" output (this will continue indefinitely)
                                this._ui.userMessage(`Watching ${this._styler.hilite(containerName)} log (CTRL-C to quit)...`);
                                let runProc = (0, child_process_1.exec)(`docker logs -f ${containerName}`);
                                (_b = runProc.stdout) === null || _b === void 0 ? void 0 : _b.addListener("data", chunk => process.stdout.write(chunk));
                                (_c = runProc.stderr) === null || _c === void 0 ? void 0 : _c.addListener("error", err => process.stderr.write(`${err.name}: ${err.stack || err.message}`));
                                (_d = runProc.stdin) === null || _d === void 0 ? void 0 : _d.addListener("data", chunk => process.stdin.write(chunk));
                            }
                            else if (flags.detach) {
                                // Stream the "docker run" output (in this case it'll start and release)
                                let runProc = (0, child_process_1.exec)(dockerCmd);
                                (_e = runProc.stdout) === null || _e === void 0 ? void 0 : _e.addListener("data", chunk => process.stdout.write(chunk));
                                (_f = runProc.stderr) === null || _f === void 0 ? void 0 : _f.addListener("error", err => process.stderr.write(`${err.name}: ${err.stack || err.message}`));
                                (_g = runProc.stdin) === null || _g === void 0 ? void 0 : _g.addListener("data", chunk => process.stdin.write(chunk));
                                this._ui.userMessage(this._styler.colorGood(`${this._styler.hilite(image)} is now available at ${this._styler.hilite(publicUrl)}`));
                            }
                            else {
                                this._ui.userMessage(this._styler.colorGood(`Running ${this._styler.hilite(image)} at address ${this._styler.hilite(publicUrl)}`));
                                // Stream the "docker run" output (this will continue indefinitely)
                                // First attempt:  using exec - doesnt show output
                                let runProc = (0, child_process_1.exec)(dockerCmd);
                                (_h = runProc.stdout) === null || _h === void 0 ? void 0 : _h.addListener("data", chunk => process.stdout.write(chunk));
                                // runProc.stderr.addListener("error", err => process.stderr.write(`${err.name}: ${err.stack||err.message}`));
                                (_j = runProc.stderr) === null || _j === void 0 ? void 0 : _j.addListener("data", chunk => process.stderr.write(chunk));
                                (_k = runProc.stdin) === null || _k === void 0 ? void 0 : _k.addListener("data", chunk => process.stdin.write(chunk));
                            }
                            resolve();
                        }
                        catch (err) {
                            reject(err);
                        }
                    }));
                }));
            }
            catch (err) {
                // TODO: Consider this instead...
                // this.logger.error(`Error parsing arguments: ${err}`);
                // this.logger.debug(err.stack);
                // return new Promise<void>(async (res,rej) => res());
                return new Promise((res, rej) => tslib_1.__awaiter(this, void 0, void 0, function* () { return rej(new Error(`Error parsing arguments: ${err}`)); }));
            }
        });
    }
    build() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    this.log(`Pretending to build...`);
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
}
exports.default = Run;
Run.description = 'Runs the latest build of the api container locally.';
/** The non-flag arguments the command supports */
Run.args = {};
Run.flags = Object.assign({ build: core_1.Flags.boolean({ char: 'b', description: 'Triggers a new local build beforehand.' }), detach: core_1.Flags.boolean({ char: 'd', description: 'Run container in background and print the container ID.' }), entrypoint: core_1.Flags.string({ char: 'e', description: 'Overrides the default container startup command.' }), help: core_1.Flags.help({ char: 'h', description: "Renders the help document for this command." }), interactive: core_1.Flags.boolean({ char: 'i', description: 'Run the container interactively (in the console; dies with the console).  Use -e|--entrypoint to override the startup command for the container.' }), network: core_1.Flags.string({ char: 'n', description: 'The docker network to which the container will be attached (defaults to a network named as the company code, which will be created on demand as a bridge network).' }), mountFolder: core_1.Flags.string({ char: 'm', required: false, description: 'Mounts a folder on the host as a read-write volume on the container. In format "src=~/my/local/folder,dst=/root/in/container".' }), port: core_1.Flags.integer({ char: 'p', description: `(default: ${ops_1.DxConstants.DEFAULT_EXTERNAL_PORT}) Sets the external port to open on the container.  That is, the port on which the api will be listening to calls from outside the container.` }), internalPort: core_1.Flags.integer({ char: 'l', description: `(default: ${ops_1.DxConstants.DEFAULT_INTERNAL_PORT}) The port the application inside the container is listening on.  Sets the port to which map incoming requests on the container.  This port mapping MUST match whatever port number the actual application is listening on.` }), watch: core_1.Flags.boolean({ char: 'w', description: 'Forces a detach run and follows log output from the container.' }) }, cli_common_1.commandBase.globalFlags);
//# sourceMappingURL=run.js.map