"use strict";
const fs = require("fs");
const path = require("path");

const prefix = "VITE_APP_";
const publicUrl = import.meta.env.PUBLIC_URL || "";
const scriptPath = path.join("./application", publicUrl, "env.js");

function generateScriptContent() {
  const prefixRegex = new RegExp(`^${prefix}`);
  const env = import.meta.env;
  const config = Object.keys(env)
    .filter(key => prefixRegex.test(key))
    .reduce((c, key) => Object.assign({}, c, { [key]: env[key] }), {});
  return `window.env=${JSON.stringify(config)};`;
}

function saveScriptContent(scriptContents) {
  fs.writeFile(scriptPath, scriptContents, "utf8", function (err) {
    if (err) throw err;
  });
}

console.log("Setting environment variables...");
const scriptContent = generateScriptContent();
saveScriptContent(scriptContent);
console.log(`Updated ${scriptPath} with ${prefix}* environment variables: ${scriptContent}.`);
