const fs = require('fs');

// 1. Force BOM on app_final.js
let jsPath = 'app_final.js';
let jsBuffer = fs.readFileSync(jsPath);
if (jsBuffer[0] !== 0xEF || jsBuffer[1] !== 0xBB || jsBuffer[2] !== 0xBF) {
    console.log('Adding BOM to app_final.js');
    fs.writeFileSync(jsPath, Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), jsBuffer]));
}

// 2. Force BOM on db.js and others just in case
['db.js', 'vouchers_returns.js'].forEach(file => {
    try {
        let buf = fs.readFileSync(file);
        if (buf[0] !== 0xEF || buf[1] !== 0xBB || buf[2] !== 0xBF) {
            fs.writeFileSync(file, Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), buf]));
        }
    } catch(e){}
});

// 3. Update query strings in index.html to bust cache
let html = fs.readFileSync('index.html', 'utf8');
const version = Date.now().toString();
html = html.replace(/v=\d+/g, 'v=' + version);

// Ensure the wipe script triggers again if they missed it, or if it triggered before we busted cache!
// We'll rename the flag.
html = html.replace('db_wiped_11', 'db_wiped_12');

fs.writeFileSync('index.html', html, 'utf8');
console.log('Cache busted and BOMs added.');
