"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");
class RegistryInitializer {
    constructor() {
        this.currentNpmrcConfig = '';
        this.npmrcUser = '';
        this.npmrcBasicAuthToken = '';
        this.npmrcPath = '';
    }
    initRegistry() {
        console.info('⟲ Initialising cplace jfrog registry for NPM');
        try {
            this.getNpmrcPath();
            if (!this.extractTokenFromEnvironment()) {
                this.extractTokenFromGradleProps();
            }
            this.initOrUpdateJfrogCredentials('@cplace-next', `${RegistryInitializer.JROG_REGISTRY_URL}`, 'cplace-npm-local', RegistryInitializer.JROG_CPLACE_NPM_REGISTRY);
            this.initOrUpdateJfrogCredentials('@cplace-3rdparty-modified', `${RegistryInitializer.JROG_REGISTRY_URL}`, RegistryInitializer.JROG_CPLACE_ASSETS_NPM_REGISTRY, RegistryInitializer.JROG_CPLACE_ASSETS_NPM_REGISTRY);
        }
        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;
    }
    extractTokenFromGradleProps() {
        console.info('⟲ Configuring npm jfrog registry via the gradle properties');
        const gradleProps = this.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');
        }
    }
    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);
    }
    getNpmrcPath() {
        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;
    }
    initOrUpdateJfrogCredentials(scope, registryUrl, oldRegistryName, newRegistryName) {
        if (!(this.npmrcUser &&
            this.npmrcBasicAuthToken &&
            this.npmrcUser.length > 0 &&
            this.npmrcBasicAuthToken.length > 0)) {
            throw Error('No jfrog credentials found.');
        }
        RegistryInitializer.createNmprcIfNotExistent(this.npmrcPath);
        this.currentNpmrcConfig = fs
            .readFileSync(this.npmrcPath, { encoding: 'utf-8' })
            .toString();
        if (!this.hasJfrogCredentials(scope, registryUrl, oldRegistryName) &&
            !this.hasJfrogCredentials(scope, registryUrl, newRegistryName)) {
            this.appendToExistingNpmrc(scope, registryUrl, newRegistryName);
        }
        else {
            this.updateNPMRC(registryUrl, oldRegistryName, newRegistryName);
        }
    }
    static createNmprcIfNotExistent(npmrcPath) {
        utils_1.debug(`Checking for npmrc at ${npmrcPath}`);
        if (!fs.existsSync(npmrcPath)) {
            fs.writeFileSync(npmrcPath, '');
            console.info(utils_1.cgreen `✓`, `Created empty .npmrc at location ${npmrcPath}`);
        }
    }
    hasJfrogCredentials(scope, registryUrl, registryName) {
        return this.currentNpmrcConfig.includes(`${scope}:registry=https:${registryUrl}${registryName}/`);
    }
    hasLatestJfrogCredentials(registryUrl) {
        return (this.currentNpmrcConfig.includes(registryUrl) &&
            this.currentNpmrcConfig.includes(this.npmrcBasicAuthToken) &&
            this.currentNpmrcConfig.includes(this.npmrcUser));
    }
    appendToExistingNpmrc(scope, registryUrl, registryName) {
        console.info('⟲ Append config to existing config at: ', this.npmrcPath);
        const fullRegistryPath = `${registryUrl}${registryName}/`;
        let npmrc = `\n${scope}:registry=https:${fullRegistryPath}\n`;
        npmrc =
            npmrc + `${fullRegistryPath}:_auth=${this.npmrcBasicAuthToken}\n`;
        npmrc = npmrc + `${fullRegistryPath}:always-auth=true\n`;
        npmrc = npmrc + `${fullRegistryPath}:email=${this.npmrcUser}\n`;
        fs.appendFileSync(this.npmrcPath, npmrc, { encoding: 'utf-8' });
        console.log(utils_1.cgreen `✓`, 'Appended config to existing config at: ', this.npmrcPath);
    }
    updateNPMRC(registryUrl, oldRegistryName, newRegistryName) {
        console.info('⟲ Updating npm config at: ', this.npmrcPath);
        this.currentNpmrcConfig = this.currentNpmrcConfig.replace(new RegExp(oldRegistryName, 'g'), newRegistryName);
        const fullRegistryPath = `${registryUrl}${newRegistryName}/`;
        const authRegex = new RegExp(fullRegistryPath.replace(/\./g, '\\.') + ':_auth *= *.*', 'i');
        this.currentNpmrcConfig = this.currentNpmrcConfig.replace(authRegex, `${fullRegistryPath}:_auth=${this.npmrcBasicAuthToken}`);
        this.currentNpmrcConfig = this.currentNpmrcConfig.replace(/^\/\/cplace.jfrog.io\/artifactory\/api\/npm\/cplace-npm\/:email *= *.*$/i, `${RegistryInitializer.JROG_REGISTRY_URL}:email=${this.npmrcUser}`);
        const userRegex = new RegExp(fullRegistryPath.replace(/\./g, '\\.') + ':email *= *.*', 'i');
        this.currentNpmrcConfig = this.currentNpmrcConfig.replace(userRegex, `${fullRegistryPath}:email=${this.npmrcUser}`);
        console.log(utils_1.cgreen `✓`, 'Updated config at: ', this.npmrcPath);
        fs.writeFileSync(this.npmrcPath, this.currentNpmrcConfig, {
            encoding: 'utf-8',
        });
    }
}
exports.RegistryInitializer = RegistryInitializer;
RegistryInitializer.JROG_CPLACE_NPM_REGISTRY = 'cplace-npm';
RegistryInitializer.JROG_CPLACE_ASSETS_NPM_REGISTRY = 'cplace-assets-npm';
RegistryInitializer.JROG_REGISTRY_URL = '//cplace.jfrog.io/artifactory/api/npm/';
RegistryInitializer.GRADLE_HOME = '.gradle';
RegistryInitializer.GRADLE_PROPERTIES = 'gradle.properties';
//# sourceMappingURL=RegistryInitializer.js.map