#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var glob = require('glob');

var args = require('optimist').argv;

var header = args.h || args.header;

var componentsDir = path.join('src', 'components');

var componentIndex = path.join('src', 'component-index.js');

var packageJson = JSON.parse(fs.readFileSync('./package.json'));

var strm = fs.createWriteStream(componentIndex);

if (header) {
   strm.write(fs.readFileSync(header));
   strm.write('\n');
}

strm.write("/*\n");
strm.write(" * THIS FILE IS AUTO-GENERATED\n");
strm.write(" * You can edit it you like, but your changes will be overwritten,\n");
strm.write(" * so you'd just be trying to swim upstream like a salmon.\n");
strm.write(" * You are not a salmon.\n");
strm.write(" */\n\n");

if (packageJson['matrix-react-parent']) {
    strm.write("module.exports.components = require('"+packageJson['matrix-react-parent']+"/lib/component-index').components;\n\n");
} else {
    strm.write("module.exports.components = {};\n");
}

var files = glob.sync('**/*.js', {cwd: componentsDir});
for (var i = 0; i < files.length; ++i) {
    var file = files[i].replace('.js', '');

    var moduleName = (file.replace(/\//g, '.'));

    strm.write("module.exports.components['"+moduleName+"'] = require('./components/"+file+"');");
    strm.write('\n');
    strm.uncork();
}

// Temporary Vector transition
var vectorViewsPath = path.join('src', 'skins', 'vector', 'views');
if (fs.existsSync(vectorViewsPath)) {
    strm.write('\n');
    strm.write('// Old, unported Vector views:\n');
    var files = glob.sync('**/*.js', {cwd: vectorViewsPath});
    for (var i = 0; i < files.length; ++i) {
        var file = files[i].replace('.js', '');

        var moduleName = (file.replace(/\//g, '.'));

        strm.write("module.exports.components['"+moduleName+"'] = require('./skins/vector/views/"+file+"');");
        strm.write('\n');
        strm.uncork();
    }
}

strm.end();


@@ -1352,598 +1352,8 @@
 %0A%7D%0A%0A
-// Temporary Vector transition%0Avar vectorViewsPath = path.join('src', 'skins', 'vector', 'views');%0Aif (fs.existsSync(vectorViewsPath)) %7B%0A    strm.write('%5Cn');%0A    strm.write('// Old, unported Vector views:%5Cn');%0A    var files = glob.sync('**/*.js', %7Bcwd: vectorViewsPath%7D);%0A    for (var i = 0; i %3C files.length; ++i) %7B%0A        var file = files%5Bi%5D.replace('.js', '');%0A%0A        var moduleName = (file.replace(/%5C//g, '.'));%0A%0A        strm.write(%22module.exports.components%5B'%22+moduleName+%22'%5D = require('./skins/vector/views/%22+file+%22');%22);%0A        strm.write('%5Cn');%0A        strm.uncork();%0A    %7D%0A%7D%0A%0A
 strm
@@ -1360,9 +1360,8 @@
 .end();%0A
-%0A

Remove temporary vector stuff as the sister PR makes it obsolete.