"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegistryInitializer = void 0;
const child_process_1 = require("child_process");
const path = require("path");
const utils_1 = require("../utils");
const fs = require("fs");
const os = require("os");
const fs_1 = require("fs");
class RegistryInitializer {
    constructor() {
        this.currentNpmrcConfig = '';
        this.npmrcUser = '';
        this.npmrcBasicAuthToken = '';
        this.npmrcPath = '';
    }
    initRegistry() {
        console.info('⟲ Initialising cplace jfrog registry for NPM');
        try {
            this.setNpmrcPath();
            if (!this.extractTokenFromEnvironment()) {
                this.extractTokenFromGradleProps();
            }
            if (!fs_1.existsSync(this.npmrcPath)) {
                RegistryInitializer.createEmptyNmprc(this.npmrcPath);
            }
            this.setCurrentNpmrcConfig();
            this.removeAllRegistryCredentials();
            this.addDefaultRegistryCredentialsToNpmrc();
        }
        catch (e) {
            console.error(utils_1.cred `✗`, e.message, 'You can ignore this for cplace versions before 5.16.');
        }
    }
    extractTokenFromEnvironment() {
        if (process.env.ENV_CPLACE_ARTIFACTORY_ACTOR &&
            process.env.ENV_CPLACE_ARTIFACTORY_TOKEN) {
            console.info('⟲ Configuring npm jfrog registry via environment variables');
            this.npmrcBasicAuthToken = Buffer.from(`${process.env.ENV_CPLACE_ARTIFACTORY_ACTOR}:${process.env.ENV_CPLACE_ARTIFACTORY_TOKEN}`).toString('base64');
            this.npmrcUser = process.env.ENV_CPLACE_ARTIFACTORY_ACTOR;
            return true;
        }
        return false;
    }
    static getGradlePropsPath() {
        const gradleHome = RegistryInitializer.getGradleHome();
        utils_1.debug(`.gradle location: ${gradleHome}`);
        if (!fs.existsSync(gradleHome)) {
            throw Error(`.gradle at location ${gradleHome} does not exist. Please use the default (${os.homedir()}/${RegistryInitializer.GRADLE_HOME}) or properly configure the environment variable GRADLE_USER_HOME.`);
        }
        const gradleProperties = path.join(gradleHome, RegistryInitializer.GRADLE_PROPERTIES);
        utils_1.debug(`gradle.properties location: ${gradleProperties}`);
        if (!fs.existsSync(gradleProperties)) {
            throw Error(`gradle.properties at location ${gradleProperties} do not exist!`);
        }
        return fs.readFileSync(gradleProperties).toString();
    }
    static getGradleHome() {
        if (process.env.GRADLE_USER_HOME) {
            return process.env.GRADLE_USER_HOME;
        }
        return path.join(os.homedir(), RegistryInitializer.GRADLE_HOME);
    }
    static createEmptyNmprc(npmrcPath) {
        fs.writeFileSync(npmrcPath, '');
        console.info(utils_1.cgreen `✓`, `Created empty .npmrc at location ${npmrcPath}`);
    }
    setCurrentNpmrcConfig() {
        this.currentNpmrcConfig = fs
            .readFileSync(this.npmrcPath, { encoding: 'utf-8' })
            .toString();
    }
    setNpmrcPath() {
        const npmConfig = child_process_1.execSync('npm config ls -l').toString();
        utils_1.debug(`Found user config ${npmConfig}`);
        const npmrcPath = (npmConfig.match(/userconfig *= *".*"/gi) || [])[0];
        if (!npmrcPath) {
            throw Error('No userconfig found in npm config');
        }
        const cleanNpmrcPath = npmrcPath
            .replace(/^userconfig *= */, '')
            .replace(/"/gi, '')
            .replace(/\\\\/g, '\\');
        if (!cleanNpmrcPath) {
            throw Error('Userconfig was found in npmrc but path can not be extracted');
        }
        this.npmrcPath = cleanNpmrcPath;
    }
    removeAllRegistryCredentials() {
        utils_1.debug(`Cleaning registries jFrog credentials`);
        if (!this.currentNpmrcConfig) {
            return;
        }
        RegistryInitializer.REGISTRY_LIST.forEach((registry) => {
            this.removeSingleRegistryCredentials(registry);
        });
    }
    removeSingleRegistryCredentials(registry) {
        utils_1.debug(`Cleaning ${registry} registry jFrog credentials`);
        const linesToRemove = this.currentNpmrcConfig
            .split('\n')
            .filter((configLine) => configLine.includes(registry));
        fs.writeFileSync(this.npmrcPath, this.getCleanedNpmrcConfig(linesToRemove), {
            encoding: 'utf-8',
        });
        this.setCurrentNpmrcConfig();
    }
    getCleanedNpmrcConfig(linesToRemove) {
        let currentNpmrcConfigLines = this.currentNpmrcConfig.split('\n');
        const indexesToRemove = [];
        currentNpmrcConfigLines.forEach((line, index) => {
            if (linesToRemove.includes(line) || !line) {
                if (index !== undefined || !line) {
                    indexesToRemove.push(index);
                }
            }
        });
        currentNpmrcConfigLines = currentNpmrcConfigLines.filter((line, lineIndex) => !indexesToRemove.some((index) => lineIndex === index));
        return currentNpmrcConfigLines.join('\n');
    }
    getFullRegistryPath(registryUrl, registryName) {
        return `${registryUrl}${registryName}/`;
    }
    getRegistryInfo(registryUrl, registryName) {
        return `registry=https:${this.getFullRegistryPath(registryUrl, registryName)}`;
    }
    getAuthInfo(registryUrl, registryName) {
        return `${this.getFullRegistryPath(registryUrl, registryName)}:_auth=${this.npmrcBasicAuthToken}`;
    }
    getAlwaysAuthInfo(registryUrl, registryName) {
        return `${this.getFullRegistryPath(registryUrl, registryName)}:always-auth=true`;
    }
    getEmailInfo(registryUrl, registryName) {
        return `${this.getFullRegistryPath(registryUrl, registryName)}:email=${this.npmrcUser}`;
    }
    extractTokenFromGradleProps() {
        console.info('⟲ Configuring npm jfrog registry via the gradle properties');
        const gradleProps = RegistryInitializer.getGradlePropsPath();
        const token = (gradleProps.match(/repo\.cplace\.apiToken *= *([a-z0-9]+)/gi) || [])[0];
        const user = (gradleProps.match(/repo\.cplace\.apiTokenUser *= *([a-z0-9@\-_\.]+)/gi) || [])[0];
        if (token && user) {
            const cleanToken = token.replace(/repo\.cplace\.apiToken *= */, '');
            this.npmrcUser = user.replace(/repo\.cplace\.apiTokenUser *= */, '');
            this.npmrcBasicAuthToken = Buffer.from(`${this.npmrcUser}:${cleanToken}`).toString('base64');
        }
        else {
            throw Error('jfrog credentials for Gradle not found or configured correctly. See the KnowledgeBase for help:\nhttps://docs.cplace.io/dev-docs/cplace-architecture/platform-component/build-system/java-artifact-based-builds/#creating-an-api-token-on-cplacejfrogio');
        }
    }
    getDefaultRegistryConfigItems() {
        return [
            this.getRegistryInfo(RegistryInitializer.JROG_REGISTRY_URL, RegistryInitializer.JROG_CPLACE_NPM_REGISTRY),
            this.getAuthInfo(RegistryInitializer.JROG_REGISTRY_URL, RegistryInitializer.JROG_CPLACE_NPM_REGISTRY),
            this.getAlwaysAuthInfo(RegistryInitializer.JROG_REGISTRY_URL, RegistryInitializer.JROG_CPLACE_NPM_REGISTRY),
            this.getEmailInfo(RegistryInitializer.JROG_REGISTRY_URL, RegistryInitializer.JROG_CPLACE_NPM_REGISTRY),
        ];
    }
    addDefaultRegistryCredentialsToNpmrc() {
        const defaultRegistryConfigurationItems = this.getDefaultRegistryConfigItems();
        let npmrc = this.currentNpmrcConfig
            .concat(`\n${defaultRegistryConfigurationItems[0]}\n`)
            .concat(`${defaultRegistryConfigurationItems[1]}\n`)
            .concat(`${defaultRegistryConfigurationItems[2]}\n`)
            .concat(`${defaultRegistryConfigurationItems[3]}\n`);
        fs.writeFileSync(this.npmrcPath, npmrc, { encoding: 'utf-8' });
        console.log(utils_1.cgreen `✓`, 'Updated config in: ', this.npmrcPath);
    }
}
exports.RegistryInitializer = RegistryInitializer;
RegistryInitializer.JROG_CPLACE_NPM_REGISTRY = 'cplace-npm';
RegistryInitializer.JROG_CPLACE_NPM_LOCAL_REGISTRY = 'cplace-npm-local';
RegistryInitializer.JROG_CPLACE_ASSETS_NPM_REGISTRY = 'cplace-assets-npm';
RegistryInitializer.JROG_REGISTRY_URL = '//cplace.jfrog.io/artifactory/api/npm/';
RegistryInitializer.PUBLIC_NPM_REGISTRY = 'registry.npmjs.org';
RegistryInitializer.GRADLE_HOME = '.gradle';
RegistryInitializer.GRADLE_PROPERTIES = 'gradle.properties';
RegistryInitializer.REGISTRY_LIST = [
    RegistryInitializer.JROG_CPLACE_NPM_REGISTRY,
    RegistryInitializer.JROG_CPLACE_NPM_LOCAL_REGISTRY,
    RegistryInitializer.JROG_CPLACE_ASSETS_NPM_REGISTRY,
    RegistryInitializer.PUBLIC_NPM_REGISTRY,
];
//# sourceMappingURL=RegistryInitializer.js.map