"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configureIngressLoadBalancer = exports.editAgentServiceConfig = exports.createAgentServiceConfig = exports.patchProvisioning = void 0;
exports.isIngressController = isIngressController;
const tslib_1 = require("tslib");
const dynamic_plugin_sdk_1 = require("@openshift-console/dynamic-plugin-sdk");
const utils_1 = require("../../../../common/utils");
const types_1 = require("../../../types");
const utils_2 = require("../../../utils");
const ASSISTED_IMAGE_SERVICE_ROUTE_PREFIX = 'assisted-image-service-multicluster-engine';
const getAssistedImageServiceRoute = (t) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a;
    let allRoutes = [];
    try {
        allRoutes = yield (0, dynamic_plugin_sdk_1.k8sListItems)({ model: types_1.RouteModel, queryParams: {} });
    }
    catch (e) {
        throw new Error(`${t('ai:Failed to save configuration')}: ${(0, utils_1.getErrorMessage)(e)}`);
    }
    const assistedImageServiceRoute = allRoutes === null || allRoutes === void 0 ? void 0 : allRoutes.find((r) => { var _a; return ((_a = r.metadata) === null || _a === void 0 ? void 0 : _a.name) === 'assisted-image-service'; });
    if (!((_a = assistedImageServiceRoute === null || assistedImageServiceRoute === void 0 ? void 0 : assistedImageServiceRoute.spec) === null || _a === void 0 ? void 0 : _a.host)) {
        throw new Error(`${t('ai:Failed to save configuration')}: ${t('ai:Can not find host of the assisted-image-service route')}`);
    }
    return assistedImageServiceRoute;
});
const getClusterDomain = (t, assistedImageServiceRoute) => {
    var _a;
    const prefix = `${ASSISTED_IMAGE_SERVICE_ROUTE_PREFIX}.`;
    const host = ((_a = assistedImageServiceRoute.spec) === null || _a === void 0 ? void 0 : _a.host) || '';
    const appsDomain = host.substring(host.indexOf(prefix) + prefix.length);
    const domain = appsDomain.substring(appsDomain.indexOf('.') + 1);
    if (!domain) {
        throw new Error(t('ai:Can not find cluster domain.'));
    }
    return domain;
};
const patchAssistedImageServiceRoute = (t, assistedImageServiceRoute, domain) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const newHost = `${ASSISTED_IMAGE_SERVICE_ROUTE_PREFIX}.nlb-apps.${domain}`;
    const labels = ((_a = assistedImageServiceRoute.metadata) === null || _a === void 0 ? void 0 : _a.labels) || {};
    labels['router-type'] = 'nlb';
    const patches = [
        {
            op: 'replace',
            path: '/spec/host',
            value: newHost,
        },
        {
            op: ((_b = assistedImageServiceRoute.metadata) === null || _b === void 0 ? void 0 : _b.labels) ? 'replace' : 'add',
            path: '/metadata/labels',
            value: labels,
        },
    ];
    try {
        yield (0, dynamic_plugin_sdk_1.k8sPatch)({
            model: types_1.RouteModel,
            resource: assistedImageServiceRoute,
            data: patches,
        });
    }
    catch (e) {
        throw new Error(`${t('ai:Failed to patch assisted-image-service route for new domain.')}: ${(0, utils_1.getErrorMessage)(e)}`);
    }
});
function isIngressController() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        try {
            yield (0, dynamic_plugin_sdk_1.k8sGet)({
                name: 'ingress-controller-with-nlb',
                ns: 'openshift-ingress-operator',
                model: types_1.IngressControllerModel,
            });
            return true;
        }
        catch (_a) {
            return false;
        }
    });
}
const createIngressController = (t, domain) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const ingressController = {
        apiVersion: 'operator.openshift.io/v1',
        kind: 'IngressController',
        metadata: {
            name: 'ingress-controller-with-nlb',
            namespace: 'openshift-ingress-operator',
        },
        spec: {
            domain: `nlb-apps.${domain}`,
            routeSelector: {
                matchLabels: {
                    'router-type': 'nlb',
                },
            },
            endpointPublishingStrategy: {
                type: 'LoadBalancerService',
                loadBalancer: {
                    scope: 'External',
                    providerParameters: {
                        type: 'AWS',
                        aws: {
                            type: 'NLB',
                        },
                    },
                },
            },
        },
    };
    try {
        yield (0, dynamic_plugin_sdk_1.k8sCreate)({ model: types_1.IngressControllerModel, data: ingressController });
    }
    catch (e) {
        throw new Error(`${t('ai:Failed to create IngressController')}: ${(0, utils_1.getErrorMessage)(e)}`);
    }
});
const patchProvisioning = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const provisioning = yield (0, dynamic_plugin_sdk_1.k8sGet)({
        model: types_1.ProvisioningModel,
        name: 'provisioning-configuration',
    });
    if ((_a = provisioning.spec) === null || _a === void 0 ? void 0 : _a.watchAllNamespaces) {
        return;
    }
    const patches = [
        {
            op: ((_b = provisioning.spec) === null || _b === void 0 ? void 0 : _b.watchAllNamespaces) === false ? 'replace' : 'add',
            path: '/spec/watchAllNamespaces',
            value: true,
        },
    ];
    yield (0, dynamic_plugin_sdk_1.k8sPatch)({
        model: types_1.ProvisioningModel,
        resource: provisioning,
        data: patches,
    });
});
exports.patchProvisioning = patchProvisioning;
const createAgentServiceConfig = (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ t, values, }) {
    try {
        const agentServiceConfig = {
            apiVersion: 'agent-install.openshift.io/v1beta1',
            kind: 'AgentServiceConfig',
            metadata: {
                name: 'agent',
                annotations: {},
            },
            spec: {
                databaseStorage: {
                    accessModes: ['ReadWriteOnce'],
                    resources: {
                        requests: {
                            storage: `${values.dbVolSize}Gi`,
                        },
                    },
                },
                filesystemStorage: {
                    accessModes: ['ReadWriteOnce'],
                    resources: {
                        requests: {
                            storage: `${values.fsVolSize}Gi`,
                        },
                    },
                },
                imageStorage: {
                    accessModes: ['ReadWriteOnce'],
                    resources: {
                        requests: {
                            storage: `${values.imgVolSize}Gi`,
                        },
                    },
                },
            },
        };
        if (values.ciscoIntersightURL) {
            agentServiceConfig.metadata = Object.assign(Object.assign({}, agentServiceConfig.metadata), { annotations: { ciscoIntersightURL: values.ciscoIntersightURL } });
        }
        yield (0, dynamic_plugin_sdk_1.k8sCreate)({
            model: types_1.AgentServiceConfigModel,
            data: agentServiceConfig,
        });
    }
    catch (e) {
        throw new Error(`${t('ai:Failed to create AgentServiceConfig')}: ${(0, utils_1.getErrorMessage)(e)}`);
    }
});
exports.createAgentServiceConfig = createAgentServiceConfig;
const editAgentServiceConfig = (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ t, agentServiceConfig, values, }) {
    var _b, _c, _d, _e, _f;
    const patches = [];
    if (((_c = (_b = agentServiceConfig.metadata) === null || _b === void 0 ? void 0 : _b.annotations) === null || _c === void 0 ? void 0 : _c['ciscoIntersightURL']) &&
        !values.ciscoIntersightURL) {
        patches.push({
            op: 'remove',
            path: '/metadata/annotations/ciscoIntersightURL',
        });
    }
    else if (!((_d = agentServiceConfig.metadata) === null || _d === void 0 ? void 0 : _d.annotations) && values.ciscoIntersightURL) {
        patches.push({
            op: 'add',
            path: '/metadata/annotations',
            value: { ciscoIntersightURL: values.ciscoIntersightURL },
        });
    }
    else if (values.ciscoIntersightURL) {
        (0, utils_2.appendPatch)(patches, '/metadata/annotations/ciscoIntersightURL', values.ciscoIntersightURL, (_f = (_e = agentServiceConfig.metadata) === null || _e === void 0 ? void 0 : _e.annotations) === null || _f === void 0 ? void 0 : _f['ciscoIntersightURL']);
    }
    if (patches.length === 0) {
        return;
    }
    try {
        yield (0, dynamic_plugin_sdk_1.k8sPatch)({
            model: types_1.AgentServiceConfigModel,
            resource: agentServiceConfig,
            data: patches,
        });
    }
    catch (e) {
        throw new Error(`${t('ai:Failed to save configuration')}: ${(0, utils_1.getErrorMessage)(e)}`);
    }
});
exports.editAgentServiceConfig = editAgentServiceConfig;
const configureIngressLoadBalancer = (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ t }) {
    if (yield isIngressController()) {
        return;
    }
    const assistedImageServiceRoute = yield getAssistedImageServiceRoute(t);
    const domain = getClusterDomain(t, assistedImageServiceRoute);
    yield createIngressController(t, domain);
    yield patchAssistedImageServiceRoute(t, assistedImageServiceRoute, domain);
});
exports.configureIngressLoadBalancer = configureIngressLoadBalancer;
//# sourceMappingURL=persist.js.map