#! /usr/bin/env node

fs = require('fs');

const dateOnly = process.argv.indexOf("--date-only") >= 0;

function getInitContent() {
    return `
    // Angular build information, automatically updated by \`node updateBuildInfo.js´
    export const buildInfo = {
        timestamp: "1/1/1970, 00:00:00",
        user: "SEI Consulting S.p.A.",
        version: "1.0.0"
    };
    `;
}

function getVersion(str) {
    var expr = /(?:version:\s*")(.*?)(?:")/gm
    return str.match(expr)[0].split("\"")[1];
}

function getNewVersion(str) {
    var expr = /(?:version:\s*")(.*?)(?:")/gm
    var arr = str.match(expr)[0].split("\"")[1].split(".");
    var buildVersion = +arr[2] + 1;
    return arr[0] + "." + arr[1] + "." + buildVersion;
}

function getTimestamp(str) {
    var expr = /(?:timestamp:\s*")(.*?)(?:")/gm
    return str.match(expr)[0].split("\"")[1];
}

const exportPath = process.cwd() + "/src/build.ts";

try {
    if (!fs.existsSync(exportPath)) {
        let content = getInitContent();
        content = content.replace(getTimestamp(content), (new Date()).toLocaleString("it-IT"));
        fs.writeFile(exportPath, content, function (err) {
            if (err) return console.log(err);
            console.log('*** File build.ts initialized with content: ', content);
        });
        return;
    }
} catch(err) {
    console.error(err);
    return;
}

let content = fs.readFileSync(exportPath, {encoding: 'utf8'});

console.info("Actual content: ", content);
if (!content)
    content = getInitContent();

var actualVersion = getVersion(content);
var newVersion = dateOnly ? actualVersion : getNewVersion(content);

console.info(`Updating version from ${actualVersion} to ${newVersion}`);

console.log("Exporting in: ", exportPath);
var newContent = content
    .replace(actualVersion, newVersion)
    .replace(getTimestamp(content), (new Date()).toLocaleString("it-IT"));


console.log("Updating build info: ", newContent);

fs.writeFile(exportPath, newContent, function (err) {
  if (err) return console.log(err);
  console.log('File generated.');
});
