#!/usr/bin/env node
/* eslint no-console: 0 */
const path = require('path');
const chalk = require('chalk');
const meow = require('meow');
const exec = require('child-process-promise').exec;
const { assets } = require('../dist/stats.json');

const sourceMaps = assets
  .map(({ name }) => name)
  .filter(name => name.endsWith('.js'));

const { RELEASE, SENTRY_AUTH_KEY } = process.env;
const SENTRY_PROJECT = 'webkom/lego-webapp';

const failedCommands = [];

const cli = meow(`
  Upload artifacts to sentry and create a release.
`);

async function run(command) {
  try {
    console.log(chalk.yellow('RUN'), command);
    return await exec(command);
  } catch (error) {
    console.error(error);
    throw new Error(command);
  }
}

async function task(promise) {
  try {
    await promise;
  } catch (error) {
    failedCommands.push(error);
  }
}

async function createSentryRelease(version, project) {
  return run(
    `curl https://sentry.abakus.no/api/0/projects/${SENTRY_PROJECT}/releases/ \
    -H 'Authorization: Bearer ${SENTRY_AUTH_KEY}' \
    -X POST -d '{"version": "${RELEASE}"}' -H 'Content-Type: application/json'`
  );
}

async function uploadSourceMap(filename) {
  const filePath = path.resolve(__dirname, '..', 'dist', filename);
  const result = await run(`
    curl https://sentry.abakus.no/api/0/projects/${SENTRY_PROJECT}/releases/${RELEASE}/files/ -X POST \
    -H 'Authorization: Bearer ${SENTRY_AUTH_KEY}' \
    -F file=@${filePath} -F name=~${filename}
  `);

  if (!JSON.parse(result.stdout).sha1) {
    throw new Error(`Upload error ${result.stdout}`);
  }

  return result;
}

async function uploadProjectToSentry() {
  await createSentryRelease();
  await Promise.all(sourceMaps.map(uploadSourceMap));
}

async function deleteSourceMaps() {
  await Promise.all(sourceMaps.map(sourceMap => run(`rm ${sourceMap}`)));
}

async function main(flags) {
  const startTime = Date.now();

  await task(uploadProjectToSentry());

  if (flags.delete) {
    // Delete sourcemaps if the --delete flag exists.
    await task(deleteSourceMaps());
  }

  if (failedCommands.length > 0) {
    console.log();
    console.log(chalk.red.bold('These commands failed:'));

    for (const error of failedCommands) {
      console.error(chalk.gray('$ '), error.message);
    }

    console.log();
    console.log(chalk.yellow('Try to run them manually.'));
  } else {
    console.log(chalk.green('All good!'), '😎');
  }

  console.log(
    chalk.green(
      `Done in ${((Date.now() - startTime) / 1000).toFixed(2)} seconds.`
    )
  );
  console.log();
}

main(cli.flags);

@@ -529,16 +529,106 @@
 e.%0A%60);%0A%0A
+function getPath(filename) %7B%0A  return path.resolve(__dirname, '..', 'dist', filename);%0A%7D%0A%0A
 async fu
@@ -1272,76 +1272,8 @@
 ) %7B%0A
-  const filePath = path.resolve(__dirname, '..', 'dist', filename);%0A
   co
@@ -1472,16 +1472,25 @@
 =@$%7B
-filePath
+getPath(filename)
 %7D -F
@@ -1812,32 +1812,37 @@
 ait Promise.all(
+%0A    
 sourceMaps.map(s
@@ -1863,16 +1863,24 @@
 n(%60rm $%7B
+getPath(
 sourceMa
@@ -1884,12 +1884,16 @@
 eMap
+)
 %7D%60))
+%0A  
 );%0A%7D

Delete sentry files correctly