"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getResultsThroughCommandRunner = exports.getAnsibleMetaData = void 0;
const vscode_uri_1 = require("vscode-uri");
const commandRunner_1 = require("./commandRunner");
const child_process = __importStar(require("child_process"));
let context;
let connection;
function getAnsibleMetaData(contextLocal, connectionLocal) {
    return __awaiter(this, void 0, void 0, function* () {
        context = contextLocal;
        connection = connectionLocal;
        const ansibleMetaData = {};
        ansibleMetaData["ansible information"] = yield getAnsibleInfo();
        ansibleMetaData["python information"] = yield getPythonInfo();
        ansibleMetaData["ansible-lint information"] = yield getAnsibleLintInfo();
        const settings = yield context.documentSettings.get(context.workspaceFolder.uri);
        if (settings.executionEnvironment.enabled) {
            ansibleMetaData["execution environment information"] =
                yield getExecutionEnvironmentInfo();
        }
        return ansibleMetaData;
    });
}
exports.getAnsibleMetaData = getAnsibleMetaData;
function getResultsThroughCommandRunner(cmd, arg) {
    return __awaiter(this, void 0, void 0, function* () {
        const settings = yield context.documentSettings.get(context.workspaceFolder.uri);
        const commandRunner = new commandRunner_1.CommandRunner(connection, context, settings);
        const workingDirectory = vscode_uri_1.URI.parse(context.workspaceFolder.uri).path;
        const mountPaths = new Set([workingDirectory]);
        let result;
        try {
            result = yield commandRunner.runCommand(cmd, arg, workingDirectory, mountPaths);
            if (result.stderr) {
                console.log(`cmd '${cmd} ${arg}' has the following error/warning: ${result.stderr}`);
                return result;
            }
        }
        catch (error) {
            console.log(`cmd '${cmd} ${arg}' was not executed with the following error: ' ${error.toString()}`);
            return undefined;
        }
        return result;
    });
}
exports.getResultsThroughCommandRunner = getResultsThroughCommandRunner;
function getAnsibleInfo() {
    return __awaiter(this, void 0, void 0, function* () {
        const ansibleInfo = {};
        const ansibleVersionObj = (yield context.ansibleConfig).ansible_meta_data;
        const ansibleVersionObjKeys = Object.keys(ansibleVersionObj);
        // return empty if ansible --version fails to execute
        if (ansibleVersionObjKeys.length === 0) {
            return ansibleInfo;
        }
        let ansibleCoreVersion;
        if (ansibleVersionObjKeys[0].includes(" [")) {
            ansibleCoreVersion = ansibleVersionObjKeys[0].split(" [");
        }
        else {
            ansibleCoreVersion = ansibleVersionObjKeys[0].split(" ");
        }
        ansibleInfo["core version"] = ansibleCoreVersion[1]
            .slice(0, -1)
            .split(" ")
            .pop()
            .trim();
        ansibleInfo["location"] = (yield context.ansibleConfig).ansible_location;
        ansibleInfo["config file path"] = ansibleVersionObj["config file"];
        ansibleInfo["collections location"] = (yield context.ansibleConfig).collections_paths;
        ansibleInfo["modules location"] = (yield context.ansibleConfig).module_locations;
        ansibleInfo["default host list path"] = (yield context.ansibleConfig).default_host_list;
        return ansibleInfo;
    });
}
function getPythonInfo() {
    return __awaiter(this, void 0, void 0, function* () {
        const pythonInfo = {};
        const pythonVersionResult = yield getResultsThroughCommandRunner("python3", "--version");
        if (pythonVersionResult === undefined) {
            return pythonInfo;
        }
        pythonInfo["version"] = pythonVersionResult.stdout
            .trim()
            .split(" ")
            .pop()
            .trim();
        const pythonPathResult = yield getResultsThroughCommandRunner("python3", '-c "import sys; print(sys.executable)"');
        pythonInfo["location"] = pythonPathResult.stdout.trim();
        return pythonInfo;
    });
}
function getAnsibleLintInfo() {
    return __awaiter(this, void 0, void 0, function* () {
        const ansibleLintInfo = {};
        let ansibleLintVersionResult = yield getResultsThroughCommandRunner("ansible-lint", "--version");
        if (ansibleLintVersionResult === undefined) {
            return ansibleLintInfo;
        }
        const ansibleLintPathResult = yield getResultsThroughCommandRunner("command -v", "ansible-lint");
        // ansible-lint version reports if a newer version of the ansible-lint is available or not
        // along with the current version itself
        // so the following lines of code are to segregate the two information into to keys
        ansibleLintVersionResult = ansibleLintVersionResult.stdout.trim().split("\n");
        const ansibleLintVersion = ansibleLintVersionResult[0];
        const ansibleLintUpgradeStatus = ansibleLintVersionResult[1]
            ? ansibleLintVersionResult[1]
            : undefined;
        ansibleLintInfo["version"] = ansibleLintVersion
            .split("using")[0]
            .trim()
            .split(" ")
            .pop()
            .trim();
        ansibleLintInfo["upgrade status"] = ansibleLintUpgradeStatus;
        ansibleLintInfo["location"] = ansibleLintPathResult.stdout.trim();
        ansibleLintInfo["config file path"] =
            context.ansibleLint.ansibleLintConfigFilePath;
        return ansibleLintInfo;
    });
}
function getExecutionEnvironmentInfo() {
    return __awaiter(this, void 0, void 0, function* () {
        const eeInfo = {};
        const basicDetails = (yield context.executionEnvironment)
            .getBasicContainerAndImageDetails;
        eeInfo["container engine"] = basicDetails.containerEngine;
        eeInfo["container image"] = basicDetails.containerImage;
        eeInfo["container image ID"] = basicDetails.containerImageId;
        let eeServiceWorking = false;
        let inspectResult;
        try {
            inspectResult = JSON.parse(child_process
                .execSync(`${basicDetails.containerEngine} inspect --format='{{json .Config}}' ${basicDetails.containerImage}`, {
                encoding: "utf-8",
            })
                .toString());
            eeServiceWorking = true;
        }
        catch (error) {
            eeServiceWorking = false;
            console.log(error);
        }
        if (eeServiceWorking) {
            eeInfo["env"] = inspectResult["Env"];
            eeInfo["working directory"] = inspectResult["WorkingDir"];
        }
        return eeInfo;
    });
}
//# sourceMappingURL=getAnsibleMetaData.js.map