const path = require('path');
const fs = require('fs');
const S3 = require('aws-sdk/clients/s3');

const {
  reports_s3_akid,
  reports_s3_sak,
  DRONE,
  DRONE_BUILD_NUMBER,
  DRONE_STAGE_NAME,
} = process.env;


if (!DRONE) {
  console.log('Not running in drone, exiting...');
  process.exit(0);
}

const s3 = new S3({
  accessKeyId: reports_s3_akid,
  secretAccessKey: reports_s3_sak,
  signatureVersion: 'v4',
});

const ROOTDIR = path.dirname(path.dirname(require.main.filename));
const MODULE = path.basename(ROOTDIR);
const OBJECT_NAME = `${DRONE_BUILD_NUMBER}/${MODULE}/${DRONE_STAGE_NAME}.html`;
const REPORT_FILE = `${ROOTDIR}/mochawesome-report/mochawesome.html`;

const uploadParams = {
  Body: fs.readFileSync(REPORT_FILE),
  Bucket: 'bitgo-sdk-test-reports',
  Key: OBJECT_NAME,
  ACL: 'public-read',
  ContentType: 'text/html',
};

s3.putObject(uploadParams, (err, data) => {
  if (err) {
    console.error(`S3 error: ${err}\n${err.stack}`);
  } else {
    console.log(`=== TEST REPORT UPLOADED SUCCESSFULLY ===`);
    console.log(`https://bitgo-sdk-test-reports.s3.amazonaws.com/${OBJECT_NAME}`);
    console.log();
  }
});


@@ -669,16 +669,152 @@
 html%60;%0A%0A
+if (!fs.existsSync(REPORT_FILE)) %7B%0A  console.warn(%60Report file '$%7BREPORT_FILE%7D' not found. Skipping test report upload...%60);%0A%7D else %7B%0A  
 const up
@@ -830,16 +830,18 @@
 s = %7B%0A  
+ 
+ 
 Body: fs
@@ -868,16 +868,18 @@
 _FILE),%0A
+  
   Bucket
@@ -906,16 +906,18 @@
 ports',%0A
+  
   Key: O
@@ -928,16 +928,18 @@
 T_NAME,%0A
+  
   ACL: '
@@ -952,16 +952,18 @@
 -read',%0A
+  
   Conten
@@ -986,12 +986,16 @@
 l',%0A
+  
 %7D;%0A%0A
+  
 s3.p
@@ -1034,16 +1034,18 @@
 a) =%3E %7B%0A
+  
   if (er
@@ -1049,24 +1049,26 @@
 (err) %7B%0A    
+  
 console.erro
@@ -1104,16 +1104,18 @@
 ack%7D%60);%0A
+  
   %7D else
@@ -1117,24 +1117,26 @@
  else %7B%0A    
+ 
+ 
 console.log(
@@ -1177,24 +1177,26 @@
 ULLY ===%60);%0A
+  
     console.
@@ -1262,24 +1262,26 @@
 CT_NAME%7D%60);%0A
+  
     console.
@@ -1293,11 +1293,16 @@
 ;%0A  
-%7D%0A
+  %7D%0A  
 %7D);%0A
+%7D
 %0A

Make sure test report exists before attempting to upload