/**
 * This task generates a .go template file with the content script.
 */

const fs = require('fs');
const console = require('console');
const config = require('./config');

console.info('Start generating the content script template');

const content = fs.readFileSync(`${config.outputDir}/${config.fileName}`).toString()
    .replace(config.contentScriptConfigurationName, config.contentScriptConfigurationTemplate);

const lines = content.split('\n');

let templateVariable = '';
lines.forEach((line, idx) => {
    const escapedLine = line.replace(/("|\\)/g, '\\$1');
    // eslint-disable-next-line prefer-template
    templateVariable += '"' + escapedLine + '\\n"';
    if (idx < lines.length - 1) {
        templateVariable += ' +\n';
    }
});

const fileContents = `// Code generated by scripts/content-script DO NOT EDIT.

package proxy

import "text/template"

const contentScript = ${templateVariable}

var contentScriptTmpl = template.Must(template.New("contentScript").Parse(contentScript))
`;

fs.writeFileSync(config.goTemplatePath, fileContents);

console.info('Finished generating the content script template');
console.info(`The template file was written to ${config.goTemplatePath}`);
