"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = updateArtifacts;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const shlex_1 = require("shlex");
const error_messages_1 = require("../../../constants/error-messages");
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const exec_1 = require("../../../util/exec");
const fs_1 = require("../../../util/fs");
const git_1 = require("../../../util/git");
const regex_1 = require("../../../util/regex");
const result_1 = require("../../../util/result");
const yaml_1 = require("../../../util/yaml");
const common_1 = require("../helmv3/common");
const schema_1 = require("./schema");
const utils_1 = require("./utils");
async function updateArtifacts({ packageFileName, updatedDeps, newPackageFileContent, config, }) {
    logger_1.logger.trace(`helmfile.updateArtifacts(${packageFileName})`);
    const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
    if (!isLockFileMaintenance &&
        (updatedDeps === undefined || updatedDeps.length < 1)) {
        logger_1.logger.debug('No updated helmfile deps - returning null');
        return null;
    }
    const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'helmfile.lock');
    const existingLockFileContent = await (0, git_1.getFile)(lockFileName);
    if (is_1.default.falsy(existingLockFileContent)) {
        logger_1.logger.debug('No helmfile.lock found');
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(packageFileName, newPackageFileContent);
        const toolConstraints = [
            {
                toolName: 'helm',
                constraint: config.constraints?.helm,
            },
            {
                toolName: 'helmfile',
                constraint: config.constraints?.helmfile ??
                    result_1.Result.parse(existingLockFileContent, schema_1.LockVersion).unwrapOrNull(),
            },
        ];
        const needKustomize = updatedDeps.some((dep) => dep.managerData?.needKustomize);
        if (needKustomize) {
            toolConstraints.push({
                toolName: 'kustomize',
                constraint: config.constraints?.kustomize,
            });
        }
        const cmd = [];
        const doc = (0, yaml_1.parseSingleYaml)(newPackageFileContent, {
            removeTemplates: true,
            customSchema: schema_1.Doc,
        });
        for (const value of (0, array_1.coerceArray)(doc.repositories).filter(utils_1.isOCIRegistry)) {
            const loginCmd = await (0, utils_1.generateRegistryLoginCmd)(value.name, `https://${value.url}`, 
            // this extracts the hostname from url like format ghcr.ip/helm-charts
            value.url.replace((0, regex_1.regEx)(/\/.*/), ''));
            if (loginCmd) {
                cmd.push(loginCmd);
            }
        }
        cmd.push(`helmfile deps -f ${(0, shlex_1.quote)(packageFileName)}`);
        await (0, exec_1.exec)(cmd, {
            docker: {},
            userConfiguredEnv: config.env,
            extraEnv: (0, common_1.generateHelmEnvs)(),
            toolConstraints,
        });
        const newHelmLockContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
        if (existingLockFileContent === newHelmLockContent) {
            logger_1.logger.debug('helmfile.lock is unchanged');
            return null;
        }
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: newHelmLockContent,
                },
            },
        ];
    }
    catch (err) {
        // istanbul ignore if
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.debug({ err }, 'Failed to update Helmfile lock file');
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
//# sourceMappingURL=artifacts.js.map