#!/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("lib/codemirror.js", function(lib) {
  return lib.replace(/CodeMirror\.version = "\d+\.\d+\.\d+"/,
                     "CodeMirror.version = \"" + number + "\"");
});
function rewriteJSON(pack) {
  return pack.replace(/"version":"\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(){});

var simple = number.slice(0, number.lastIndexOf("."));

rewrite("doc/compress.html", function(cmp) {
  return cmp.replace(/<option value="http:\/\/codemirror.net\/">HEAD<\/option>/,
                     "<option value=\"http://codemirror.net/\">HEAD</option>\n        <option value=\"http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=" + number + ";f=\">" + simple + "</option>");
});

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