#!/usr/bin/node

var glob = require('glob');
var fs = require('fs-extra');
var path = require('path');
var archiver = require('archiver');

let lang = process.argv[2];

if (lang == null)
{
	let baseName = path.basename(process.argv[1]);
	console.log(`Usage: ${baseName} language_code`);
	process.exit(1);
}

let nTasks;
let projectDir;

(async () => {
	await fs.remove(lang);
	projectDir = await fs.realpath(`${__dirname}/..`);

	projectDir = realPath;
	let len = projectDir.length + 1;
	
	glob(`${projectDir}/**/locale/`, async (err, localeDirs) => {
		if (err) throw err;

		for (let localeDir of localeDirs) {
			localeDir = localeDir.substr(len)

			if (/^node_modules\//.test (localeDir))
				continue;

			await exportLocale(localeDir);
		}

		nTasks = localeDirs.length;
	});
})();

async function exportLocale (localeDir) {
	let dstDir = `${lang}/${localeDir}`;
	
	try {
		await fs.mkdirp(dstDir);

		let src, dst;
		
		src = `${projectDir}/${localeDir}/en.json`;
		dst = `${dstDir}/en.json`;
		fs.copy(src, dst, onTaskEnd);

		src = `${projectDir}/${localeDir}/${lang}.json`;
		dst = `${dstDir}/${lang}.json`;
		fs.copy(src, dst, onTaskEnd);

		nTasks += 2;
	}
	catch (e) {
		console.log(err);
	}

	nTasks--;
	if (nTasks > 0) return;

	let output = fs.createWriteStream(`${lang}.zip`);
	output.on ('close', () =>{
		fs.remove(lang);
		console.log ('Export finalized!');
	});

	let archive = archiver('zip', {
		zlib: { level: 9 }
	});
	archive.on ('error', err => {
		throw err;
	});
	archive.pipe(output);
	archive.directory(lang);
	archive.finalize();
}
