/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/**
 * Prepare a distribution folder prior for publishing.
 */
var fs = require('fs');
var parse = require('xml-parser');
var cpy = require('cpy');
var copy = require('recursive-copy');

// Get command line arguments
var args = process.argv.slice(2);
var publishType = args[0];
if (typeof publishType === 'undefined') {
  return;
}

// The folder whose contents will be published
var distFolder = 'target/dist/';

// Copy files to the distribution folder
cpy(['package.json', '*.md'], distFolder);
// Once the distribution files are ready, apply any further updates to them.
copy('lib', distFolder, updateDist);

////////////////////////////////////////////////////////////////////////////////

/**
 * Modify files in the distribution folder.
 */
function updateDist() {
  // Get the package.json contents
  var packagePath = distFolder + 'package.json';
  var packageContent = fs.readFileSync(packagePath, 'utf8');
  var package = JSON.parse(packageContent);

  package = remapMain(package);
  package = updateVersion(package);
  package = slimDown(package);

  // Save the updated package.json.
  var newPackageContent = JSON.stringify(package);
  fs.writeFileSync(packagePath, newPackageContent, 'utf8');
}

/**
 * Point to the new index.js location.
 */
function remapMain(package) {
  package.main = 'index.js';

  return package;
}

/**
 * Update the version in the package descriptor to match the POM's.
 */
function updateVersion(package) {
  // pom.xml path
  var pomPath = './pom.xml';

  var pomContent = fs.readFileSync(pomPath, 'utf8');
  var pom = parse(pomContent);
  // Find the element that contains the version tag.
  var baseElement = pom.root.children.filter(function(item) {
    return item.name === 'parent';
  })[0];
  // If there was no `parent` tag, use the //project/version tag.
  if (typeof baseElement === 'undefined') {
    baseElement = pom.root;
  }
  // Get the version tag.
  var pomElement = baseElement.children.filter(function(item) {
    return item.name === 'version';
  })[0];
  var pomVersion = pomElement.content;
  console.log('Version in POM is ' + pomVersion);

  // Set the new package.json's version, eventually replacing the -SNAPSHOT
  // fragment, so that a snapshot can be deployed to Nexus multiple times.
  if (publishType === 'release') {
      package.version = pomVersion.replace('-SNAPSHOT', '');
  } else {
      package.version = pomVersion.replace('-SNAPSHOT', '-patch.' + new Date().getTime());
  }

  console.log('Version in package.json is now ' + package.version);

  return package;
}

/**
 * Remove unnecessary bits from the package descriptor.
 */
function slimDown(package) {
  delete package.scripts;
  delete package.devDependencies;
  delete package.private;

  return package;
}
