const os = require('os');

const { isWebClientLegacy } = require('../config');
const { bash, script } = require('../helpers/cli');
const { debug, info } = require('../helpers/log')('proton-bundler');

const SOURCE_FILE_INDEX = "find dist -maxdepth 1 -type f -name 'index*.js'";

/**
 * Get the configuration for a deployement
 *     [Warning] you must have  NODE_ENV=production
 * @param  {Array} flags flags used to bundle
 * @return {Object}       app's config
 */
async function getNewConfig(api, flags = process.argv.slice(3), isCurrent = false) {
    if (isWebClientLegacy()) {
        const branch = !isCurrent ? api.replace('+proxy', '') : 'dev';
        const { stdout = '' } = await bash('NODE_ENV=dist ./tasks/setupConfig.js', [
            '--print-config',
            `--branch deploy-${branch}`,
            ...flags
        ]);
        debug(stdout, 'stdout config angular');

        /*
            We need to rename the key sentry.sentry to sentry.dsn to match new config format from proton-pack
            because only Legacy Angular is with this weird format.
         */
        const { sentry = {}, ...json } = JSON.parse(stdout);
        const { sentry: dsn } = sentry;
        const newConfig = {
            ...json,
            sentry: {
                ...sentry,
                dsn
            }
        };

        debug(newConfig, 'new config angular with right dsn');

        return newConfig;
    }

    // we don't use npx as for the CI we cached it so it's faster
    const { stdout = '' } = await bash('./node_modules/proton-pack/bin/protonPack print-config', flags);
    debug(stdout, 'stdout config app');
    return JSON.parse(stdout);
}

function sed(rule, files) {
    // Because for the lulz. cf https://myshittycode.com/2014/07/24/os-x-sed-extra-characters-at-the-end-of-l-command-error/
    if (os.platform() === 'darwin') {
        return bash(`sed -i '' '${rule}' $(${files})`);
    }
    return bash(`sed -i '${rule}' "$(${files})"`);
}

async function writeNewConfig(api) {
    const {
        sentry: { dsn: currentSentryDSN },
        secureUrl: currentSecureURL
    } = await getNewConfig(api, ['--api proxy'], true);
    const {
        apiUrl,
        sentry: { dsn: newSentryDSN },
        secureUrl: newSecureURL
    } = await getNewConfig(api);

    debug({
        current: {
            currentSentryDSN,
            currentSecureURL
        },
        newConfig: {
            newSentryDSN,
            newSecureURL
        }
    });

    if (isWebClientLegacy()) {
        await sed(`s#apiUrl:"/api"#apiUrl:"${apiUrl}"#;`, SOURCE_FILE_INDEX);
        info(`replace current api by ${apiUrl} inside the main index`);

        await sed(`s#sentry:"${currentSentryDSN}"#sentry:"${newSentryDSN}"#;`, SOURCE_FILE_INDEX);
        info('replace sentry config inside the main index');

        await sed(`s#secure:"${currentSecureURL}"#secure:"${newSecureURL}"#;`, SOURCE_FILE_INDEX);
        return info('replace secureURL config inside the main index');
    }

    await sed(`s#="/api"#="${apiUrl}"#;`, SOURCE_FILE_INDEX);
    info(`replace current api by ${apiUrl} inside the main index`);

    await sed(`s#="${currentSentryDSN}"#="${newSentryDSN}"#;`, SOURCE_FILE_INDEX);
    info('replace sentry config inside the main index');

    await sed(`s#="${currentSecureURL}"#="${newSecureURL}"#;`, SOURCE_FILE_INDEX);
    info('replace secureURL config inside the main index');
}

/**
 * Create a new bundle from an existing one
 * To validate the bundle, we use SRI <3 <3 <3 it's easy to validate a new build with them.
 * They crash if it doesn't match <3 <3 <3
 *     - Generate hash for files with the modifications
 *     - Replace them inside index.js
 *     - Then we replace the SRI of index.js inside index.html
 * @return {Promise}
 */
async function main({ api }) {
    await bash('cp -r dist distProd');
    info('made a copy of the current dist');

    await writeNewConfig(api);

    const { stdout } = await script('manageSRI.sh write-html');
    info('update new index.html');
    debug(stdout, 'write new SRIs HTML');

    const { stdout: stdoutSed } = await script('manageSRI.sh write-env', [api]);
    info('update new .env');
    debug(stdoutSed, 'write new APP_ENV');

    /**
     * Check if the sub-build is valid
     *     - Correct SRI for updated files
     *     - Correct SRI for the index
     *     - Right config for A/B
     *     - Right config for Sentry
     * Stop the process if it fails
     */
    await script('manageSRI.sh validate', [api]);
}

module.exports = main;

@@ -553,105 +553,1096 @@
     
-if (isWebClientLegacy()) %7B%0A        const branch = !isCurrent ? api.replace('+proxy', '') : 'dev';
+debug(%7B api, flags, isCurrent %7D, 'flags getNewConfig');%0A    if (isWebClientLegacy()) %7B%0A        /**%0A         * Compat layer for old build as it binds dev API env instead of old :/%0A         * It doesn't make sense, but the main thing is we should upgrade the config setup on legacy%0A         * to match how it's done via proton-pack today for the react applications.%0A         * It will be easier to use than what we have today, build on top of obsolete config -%3E branches%0A         * so quick and dirty is the way sadly%0A         */%0A        const getBranch = () =%3E %7B%0A            if (api.includes('old')) %7B%0A                return api.replace('+proxy', '');%0A            %7D%0A            return !isCurrent ? api.replace('+proxy', '') : 'dev';%0A        %7D;%0A%0A        const branch = getBranch();%0A        const cleanApi = (api) =%3E %7B%0A            // When we deploy to these targets we must use the proxy api%0A            if (/prod%7Cold%7Cbeta%7Ctor/.test(api) && api.includes('+proxy')) %7B%0A                return (item) =%3E item.replace(/%5Cw+%5C+proxy/, 'proxy');%0A            %7D%0A            return (a) =%3E a;%0A        %7D;%0A
 %0A   
@@ -1814,16 +1814,35 @@
 ...flags
+.map(cleanApi(api))
 %0A       
@@ -2332,32 +2332,32 @@
   %7D%0A        %7D;%0A%0A
+
         debug(ne
@@ -2399,25 +2399,24 @@
 ight dsn');%0A
-%0A
         retu

Fix legacy env proxy api detection (#28)