importPackage(java.lang);
importPackage(java.io);

args = {};
for (var i = 0; i < arguments.length; i++) {
    var arg = /^(.+)=(.*)$/.exec(arguments[i]);
    args[arg[1]] = arg[2];
}

var files = (new File(args.source)).listFiles(new FileFilter() {
    accept: function(file) {
        return file.isFile() && /^[^.]+\.(html|js|css|xml)$/.exec(file.getName());
    }
});
if (!files) {
    throw(args.source + " not a directory.");
}
var data = {}, names = {};
for (var i = 0; i < files.length; i++) {
    var name = /^((.*)(\.[^.]+))$/.exec(files[i].getName());
//    print("hashing " + name);
    if (!name) continue;
    var file = data[name[1]] = readFile(files[i].getPath(), "UTF-8");
    names[name[1]] = name[2] + "." + hex(hash(file)) + name[3];
}
for (var i in data) {
    var dest = args.dest + names[i];
//    print("writing " + i + " to " + dest);
    writeFile(dest, data[i].replace(/(.+?)/g, function(_, name) {
        if (!(name in names))
            print("Unhashed file " + name + " referenced in " + i);
        return names[name];
    }));
}

function hash(s) { return (new java.lang.String(s)).hashCode(); }

function hex(n) {
    return String.fromCharCode(h(n >> 28), h(n >> 24), h(n >> 20), h(n >> 16),
                               h(n >> 12), h(n >> 8), h(n >> 4), h(n));
    function h(n) {
        n &= 15;
        return n > 9 ? n + 87 : n + 48;
    }
}

function writeFile(filename, data) {
    var fos = new FileOutputStream(filename);
    fos.write((new java.lang.String(data)).getBytes("UTF-8"));
    fos.close();
}