#!/usr/bin/env node

var fs = require("fs"), child = require("child_process");

var number, bumpOnly;

for (var i = 2; i < process.argv.length; i++) {
  if (process.argv[i] == "-bump") bumpOnly = true;
  else if (/^\d+\.\d+\.\d+$/.test(process.argv[i])) number = process.argv[i];
  else { console.log("Bogus command line arg: " + process.argv[i]); process.exit(1); }
}

if (!number) { console.log("Must give a version"); process.exit(1); }

function rewrite(file, f) {
  fs.writeFileSync(file, f(fs.readFileSync(file, "utf8")), "utf8");
}

rewrite("src/edit/main.js", function(lib) {
  return lib.replace(/CodeMirror\.version = "\d+\.\d+\.\d+"/,
                     "CodeMirror.version = \"" + number + "\"");
});
function rewriteJSON(pack) {
  return pack.replace(/"version":\s*"\d+\.\d+\.\d+"/, "\"version\": \"" + number + "\"");
}
rewrite("package.json", rewriteJSON);
rewrite("doc/manual.html", function(manual) {
  return manual.replace(/>version \d+\.\d+\.\d+<\/span>/, ">version " + number + "</span>");
});

if (bumpOnly) process.exit(0);

child.exec("bash bin/authors.sh", function(){});

rewrite("index.html", function(index) {
  return index.replace(/\.zip">\d+\.\d+\.\d+<\/a>/,
                       ".zip\">" + number + "</a>");
});
