"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withCustomizedAndSoftwareSpec = void 0;
var relative_time_1 = require("@cocalc/util/relative-time");
var hof_1 = require("async-await-utils/hof");
var compute_components_json_1 = __importDefault(require("dist/inventory/compute-components.json"));
var compute_inventory_json_1 = __importDefault(require("dist/inventory/compute-inventory.json"));
var with_customize_1 = __importDefault(require("lib/with-customize"));
var path_1 = require("path");
var fs_1 = require("fs");
var readFile = fs_1.promises.readFile;
function file2json(path) {
    return __awaiter(this, void 0, void 0, function () {
        var data;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, readFile(path, "utf8")];
                case 1:
                    data = _a.sent();
                    return [2 /*return*/, JSON.parse(data)];
            }
        });
    });
}
// load the current version of the software specs – if there is a problem, use the locally stored files as fallback.
// both files go hand-in-hand, hence either both work or both are the fallback!
function fetchInventory() {
    return __awaiter(this, void 0, void 0, function () {
        var localSpec, urlI, urlC, _a, respI, respC, inventory, components, err_1;
        var _b;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    localSpec = process.env.COCALC_COMPUTE_ENV_SPEC;
                    if (!(localSpec != null)) return [3 /*break*/, 3];
                    // read compute-inventory.json and compute-components.json from the local filesystem
                    console.log("reading inventory information from directory ".concat(localSpec));
                    _b = {};
                    return [4 /*yield*/, file2json("".concat(localSpec, "/compute-inventory.json"))];
                case 1:
                    _b.inventory = _c.sent();
                    return [4 /*yield*/, file2json("".concat(localSpec, "/compute-components.json"))];
                case 2: return [2 /*return*/, (_b.components = _c.sent(),
                        _b)];
                case 3:
                    urlI = "https://storage.googleapis.com/cocalc-compute-environment/compute-inventory.json";
                    urlC = "https://storage.googleapis.com/cocalc-compute-environment/compute-components.json";
                    _c.label = 4;
                case 4:
                    _c.trys.push([4, 10, , 11]);
                    return [4 /*yield*/, Promise.all([fetch(urlI), fetch(urlC)])];
                case 5:
                    _a = __read.apply(void 0, [_c.sent(), 2]), respI = _a[0], respC = _a[1];
                    if (!(respI.ok && respC.ok)) return [3 /*break*/, 8];
                    return [4 /*yield*/, respI.json()];
                case 6:
                    inventory = _c.sent();
                    return [4 /*yield*/, respC.json()];
                case 7:
                    components = _c.sent();
                    console.log("successfully fetched and loaded software environment config files");
                    return [2 /*return*/, { inventory: inventory, components: components }];
                case 8:
                    console.log("Error fetching inventory: ".concat(respI.status, ": ").concat(respI.statusText, "."));
                    throw Error("problem");
                case 9: return [3 /*break*/, 11];
                case 10:
                    err_1 = _c.sent();
                    console.log("Error fetching inventory: ".concat(err_1, " -- using fallback."));
                    return [2 /*return*/, {
                            inventory: compute_inventory_json_1.default,
                            components: compute_components_json_1.default,
                        }];
                case 11: return [2 /*return*/];
            }
        });
    });
}
// cached instance
var SPEC;
var SoftwareEnvSpecs;
var SoftwareEnvSpecsTimestamp = 0;
var fetchSoftwareSpec = (0, hof_1.reuseInFlight)(function () {
    return __awaiter(this, void 0, void 0, function () {
        var _a, inventory, components;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, fetchInventory()];
                case 1:
                    _a = _b.sent(), inventory = _a.inventory, components = _a.components;
                    SoftwareEnvSpecs = { inventory: inventory, components: components };
                    SoftwareEnvSpecsTimestamp = Date.now();
                    return [2 /*return*/];
            }
        });
    });
});
function getSoftwareInfo() {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!(SoftwareEnvSpecs != null)) return [3 /*break*/, 1];
                    if (SoftwareEnvSpecsTimestamp > (0, relative_time_1.hours_ago)(1).getTime()) {
                        // fresh enough, just return it
                        return [2 /*return*/, SoftwareEnvSpecs];
                    }
                    else {
                        // we asynchroneously fetch to refresh, but return the data immediately to the client
                        fetchSoftwareSpec();
                        return [2 /*return*/, SoftwareEnvSpecs];
                    }
                    return [3 /*break*/, 3];
                case 1: return [4 /*yield*/, fetchSoftwareSpec()];
                case 2:
                    _a.sent();
                    return [2 /*return*/, SoftwareEnvSpecs];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function getSoftwareInfoLang(lang) {
    return __awaiter(this, void 0, void 0, function () {
        var _a, inventory, components;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, getSoftwareInfo()];
                case 1:
                    _a = _b.sent(), inventory = _a.inventory, components = _a.components;
                    return [2 /*return*/, { inventory: inventory[lang], components: components[lang] }];
            }
        });
    });
}
// during startup, we fetch getSoftwareSpec() once to fill the cache…
(function () {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            fetchSoftwareSpec(); // not blocking
            return [2 /*return*/];
        });
    });
})();
function getSoftwareSpec() {
    return __awaiter(this, void 0, void 0, function () {
        var nextSpec, inventory, cmd, info, base;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (SPEC != null)
                        return [2 /*return*/, SPEC];
                    nextSpec = {};
                    return [4 /*yield*/, getSoftwareInfo()];
                case 1:
                    inventory = (_a.sent()).inventory;
                    for (cmd in inventory.language_exes) {
                        info = inventory.language_exes[cmd];
                        if (nextSpec[info.lang] == null) {
                            nextSpec[info.lang] = {};
                        }
                        base = cmd.indexOf(" ") > 0 ? cmd : (0, path_1.basename)(cmd);
                        nextSpec[info.lang][base] = {
                            cmd: cmd,
                            name: info.name,
                            doc: info.doc,
                            url: info.url,
                        };
                    }
                    SPEC = nextSpec;
                    return [2 /*return*/, SPEC];
            }
        });
    });
}
// this is for the server side getServerSideProps function
function withCustomizedAndSoftwareSpec(context, lang, executableInfo) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function () {
        var _c, customize, spec, inventory, _d, inventory, components, inventory, executableInfo_1, executableInfo_1_1, cmd;
        var e_1, _e;
        return __generator(this, function (_f) {
            switch (_f.label) {
                case 0: return [4 /*yield*/, Promise.all([
                        (0, with_customize_1.default)({ context: context }),
                        getSoftwareSpec(),
                    ])];
                case 1:
                    _c = __read.apply(void 0, [_f.sent(), 2]), customize = _c[0], spec = _c[1];
                    if (!(lang === "executables")) return [3 /*break*/, 3];
                    return [4 /*yield*/, getSoftwareInfo()];
                case 2:
                    inventory = (_f.sent()).inventory;
                    customize.props.executablesSpec = inventory.executables;
                    return [2 /*return*/, customize];
                case 3:
                    customize.props.spec = spec[lang];
                    return [4 /*yield*/, getSoftwareInfoLang(lang)];
                case 4:
                    _d = _f.sent(), inventory = _d.inventory, components = _d.components;
                    customize.props.inventory = inventory;
                    customize.props.components = components;
                    _f.label = 5;
                case 5:
                    if (!(executableInfo != null)) return [3 /*break*/, 7];
                    return [4 /*yield*/, getSoftwareInfo()];
                case 6:
                    inventory = (_f.sent()).inventory;
                    customize.props.execInfo = {};
                    try {
                        for (executableInfo_1 = __values(executableInfo), executableInfo_1_1 = executableInfo_1.next(); !executableInfo_1_1.done; executableInfo_1_1 = executableInfo_1.next()) {
                            cmd = executableInfo_1_1.value;
                            customize.props.execInfo[cmd] = (_b = (_a = inventory.executables) === null || _a === void 0 ? void 0 : _a[cmd]) !== null && _b !== void 0 ? _b : null;
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (executableInfo_1_1 && !executableInfo_1_1.done && (_e = executableInfo_1.return)) _e.call(executableInfo_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    _f.label = 7;
                case 7: return [2 /*return*/, customize];
            }
        });
    });
}
exports.withCustomizedAndSoftwareSpec = withCustomizedAndSoftwareSpec;
//# sourceMappingURL=software-specs.js.map