"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 (g && (g = 0, op[0] && (_ = 0)), _) 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 });
exports.DockerService = void 0;
var fs = require("fs");
var path = require("path");
var ssh_service_1 = require("./ssh.service");
var Kafka = require('kafkajs').Kafka;
var axios = require('axios');
var exec = require('child_process').exec;
var sshService = new ssh_service_1.SshService();
var clients = {};
function myExec(command) {
    return new Promise(function (resolve, reject) {
        exec(command, (function (stderr, stdout) {
            resolve({
                stderr: stderr || null,
                stdout: stdout || '',
            });
        }));
    });
}
function loadJson(path, defaultValue) {
    if (defaultValue === void 0) { defaultValue = null; }
    return __awaiter(this, void 0, void 0, function () {
        var content;
        return __generator(this, function (_a) {
            content = fs.readFileSync(path, 'utf-8');
            // console.log('content', content)
            if (content) {
                return [2 /*return*/, JSON.parse(content)];
            }
            return [2 /*return*/, defaultValue];
        });
    });
}
var USER_HOME = process.env.HOME || process.env.USERPROFILE;
var yunserFolder = path.resolve(USER_HOME, '.yunser'); // TODO package，npm install cmd-core
if (!fs.existsSync(yunserFolder)) {
    // console.log('创建目录')
    fs.mkdirSync(yunserFolder);
}
var appFolder = path.resolve(yunserFolder, 'dms-cli'); // TODO package，npm install cmd-core
if (!fs.existsSync(appFolder)) {
    fs.mkdirSync(appFolder);
}
var redisConnectionFilePath = path.resolve(appFolder, 'docker.connection.json');
if (!fs.existsSync(redisConnectionFilePath)) {
    fs.writeFileSync(redisConnectionFilePath, '[]', 'utf8');
}
var DockerService = /** @class */ (function () {
    function DockerService() {
    }
    DockerService.prototype.index = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'docker home'];
            });
        });
    };
    DockerService.prototype.run = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var command, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        command = body.command;
                        return [4 /*yield*/, myExec(command)];
                    case 1:
                        res = _a.sent();
                        console.log('res', res);
                        return [2 /*return*/, __assign({}, res)];
                }
            });
        });
    };
    DockerService.prototype.connectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadJson(redisConnectionFilePath, [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    DockerService.prototype.containers = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getList(body, '/containers/json?all=1')];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.containerStop = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._post(body, "/containers/".concat(id, "/stop"))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.containerStart = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._post(body, "/containers/".concat(id, "/start"))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.volumeDetail = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._getObject(body, "/volumes/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.containerRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._delete(body, "/containers/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.imageRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._delete(body, "/images/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.networkRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._delete(body, "/networks/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.serviceRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._delete(body, "/services/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.volumeRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = body.id;
                        return [4 /*yield*/, this._delete(body, "/volumes/".concat(id))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.images = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getList(body, '/images/json')];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.services = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getList(body, '/services')];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.networks = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getList(body, '/networks')];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype.volumes = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getList(body, '/volumes')];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DockerService.prototype._getObject = function (body, path, method) {
        if (method === void 0) { method = 'GET'; }
        return __awaiter(this, void 0, void 0, function () {
            var res, _a, stderr, stdout, m, obj;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this._command(body, "curl -i -s --unix-socket /var/run/docker.sock -X ".concat(method, " http://localhost").concat(path))];
                    case 1:
                        res = _b.sent();
                        _a = res.data, stderr = _a.stderr, stdout = _a.stdout;
                        m = stdout.match(/\r\n\r\n/);
                        obj = JSON.parse(stdout.substring(m.index));
                        return [2 /*return*/, obj];
                }
            });
        });
    };
    DockerService.prototype._getList = function (body, path, method) {
        if (method === void 0) { method = 'GET'; }
        return __awaiter(this, void 0, void 0, function () {
            var res, _a, stderr, stdout, m, _list;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this._command(body, "curl -i -s --unix-socket /var/run/docker.sock -X ".concat(method, " http://localhost").concat(path))];
                    case 1:
                        res = _b.sent();
                        console.log('_getList/res', res);
                        _a = res.data, stderr = _a.stderr, stdout = _a.stdout;
                        m = stdout.match(/\r\n\r\n/);
                        _list = JSON.parse(stdout.substring(m.index));
                        return [2 /*return*/, {
                                list: _list,
                            }];
                }
            });
        });
    };
    DockerService.prototype._post = function (body, path) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._command(body, "curl -i -s --unix-socket /var/run/docker.sock -X POST http://localhost".concat(path))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    DockerService.prototype._delete = function (body, path) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._command(body, "curl -i -s --unix-socket /var/run/docker.sock -X DELETE http://localhost".concat(path))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    DockerService.prototype._command = function (body, command) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, list, item, type, url, sshId, ret, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = body.connectionId;
                        return [4 /*yield*/, loadJson(redisConnectionFilePath, [])];
                    case 1:
                        list = _a.sent();
                        if (!connectionId) {
                            throw new Error('connectionId required');
                        }
                        item = list.find(function (item) { return item.id == connectionId; });
                        if (!item) {
                            throw new Error('connectionId error');
                        }
                        type = item.type, url = item.url;
                        if (!(type == 'ssh')) return [3 /*break*/, 3];
                        sshId = item.sshId;
                        if (!sshId) {
                            throw new Error('sshId required');
                        }
                        return [4 /*yield*/, sshService._exec({
                                id: sshId,
                                command: command,
                            })];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {
                                data: ret,
                            }];
                    case 3: return [4 /*yield*/, axios.post("".concat(url, "/docker/run"), {
                            "command": command,
                        })
                        // console.log('res', res)
                        // data: { stderr, stdout }
                    ];
                    case 4:
                        res = _a.sent();
                        // console.log('res', res)
                        // data: { stderr, stdout }
                        return [2 /*return*/, res];
                }
            });
        });
    };
    return DockerService;
}());
exports.DockerService = DockerService;
//# sourceMappingURL=docker.service.js.map