#! /usr/bin/env node

const commandLineArgs = require('command-line-args');
const checkForExistingRelease = require('./functions/checkForExistingRelease');
const createS3Client = require('./functions/createS3Client');
const promiseWrapUploader = require('./functions/promiseWrapUploader');

const optionDefinitions = [
  { name: 'bucket', alias: 'b', type: String },
  { name: 'dev', alias: 'd', type: Boolean },
  { name: 'player', type: Boolean},
  { name: 'prefix', alias: 'p', type: String },
  { name: 'root', alias: 'r', type: String },
  { name: 'target', alias: 't', type: String },
  { name: 'version', alias: 'v', type: String },
];

const options = commandLineArgs(optionDefinitions);
const pkg = require(`${options.root}/package.json`);
// const version = options.dev ? pkg.version_dev : pkg.version;

function syncDist(target, bucket, prefix) {
  let uploadOptions = {
    localDir: 'dist/' + target,

    deleteRemoved: false, // keep older versions
    s3Params: {
      Bucket: bucket,
      Prefix: prefix,
      // can add options for putObject command
      // see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
    }
  };

  let s3Client = createS3Client(pkg, `${options.root}/aws.private.json`);

  return checkForExistingRelease(s3Client, bucket, prefix).then(function () {
    console.log('DEPLOY'); return; // todo remove

    return promiseWrapUploader(s3Client.uploadDir(uploadOptions))
      .catch(function (error) {
        console.error('There was an error during the release process!');
        console.error(error.stack);
        return null;
      })
      .then(function (result) {
        if (result == null) {
          return;
        }
        console.log('Release finished');
      });
  }).catch(function(){console.log('CANCELED')});
}


syncDist(options.target, options.bucket, options.prefix);
