#!/usr/bin/env node

var path = require('path');
var fs = require('fs');
var cp = require('child_process');

var extensionDirectory = process.argv[2];
if (!extensionDirectory) {
	console.error('No extension directory provided.');
	process.exit(1)
}
extensionDirectory = path.resolve(extensionDirectory)
if (!fs.existsSync(extensionDirectory)) {
	console.error('Extension directory ' + extensionDirectory + ' doesn\'t exist on disk.');
	process.exit(1);
}

var packageFile = process.argv[3];
if (!packageFile) {
	console.error('No package.json file provided.');
	process.exit(1);
}
packageFile = path.resolve(packageFile);
if (!fs.existsSync(packageFile)) {
	console.error('Package file ' + packageFile + ' doesn\'t exist on disk.');
	process.exit(1);
}
var tsconfigFile = process.argv[4];
if (!tsconfigFile) {
	console.error('No tsconfig.json file provided');
	process.exit(1);
}
tsconfigFile = path.resolve(tsconfigFile);
if (!fs.existsSync(tsconfigFile)) {
	console.error('tsconfig file ' + tsconfigFile + ' doesn\'t exist on disk.')
	process.exit(1);
}

var extensionServerDirectory = path.join(extensionDirectory, 'server')

var json = require(tsconfigFile);
var compilerOptions = json.compilerOptions;
if (compilerOptions) {
	var outDir = compilerOptions.outDir;
	if (!outDir || path.join(path.dirname(tsconfigFile), outDir) !== extensionServerDirectory) {
		console.error('outDir in ' + process.argv[4] + ' must point to ' + extensionServerDirectory + ' but it points to ' + path.join(path.dirname(tsconfigFile), outDir));
		console.error('Please change outDir in ' + process.argv[4] + ' to ' + path.relative(path.dirname(tsconfigFile), extensionServerDirectory).replace(/\\/g, '/'));
		process.exit(1);
	}
}

if (!fs.existsSync(extensionServerDirectory)) {
	fs.mkdirSync(extensionServerDirectory);
}

var dest = path.join(extensionServerDirectory, 'package.json');
console.log('Copying package.json to extension\'s server location...');
fs.writeFileSync(dest, fs.readFileSync(packageFile));

console.log('Updating server npm modules into extension\'s server location...');
cp.execSync('npm update --production --prefix ' + extensionServerDirectory);