const Minio = require('minio');
const path = require('path');
const moment = require('moment');
const fs = require('fs/promises');
const pkg = require('../package.json');

const dirUpload = path.join(__dirname, '../dist');

const dirParent = moment().format('YYYY-MM-DD HH-mm').toString();

const bucketName = process.env.S3_BUCKET;

const connect = {
  endPoint: process.env.S3_ENDPOINT,
  port: Number(process.env.S3_PORT),
  accessKey: process.env.S3_ACCESS_KEY,
  secretKey: process.env.S3_SECRET_KEY,
  useSSL: !!(process.env.S3_SSL && process.env.S3_SSL === 'on'),
};

console.log({
  msg: 'S3_UPLOAD',
  ...connect,
  secretKey: '******',
});

const client = new Minio.Client(connect);

client.setRequestOptions({ timeout: 300000 });

fs.readdir(dirUpload)
  .then((listFile) => {
    listFile.filter((f) => f.endsWith('.zip')).forEach((fileName) => {
      const metaData = {};
      const fileRaw = path.join(dirUpload, fileName);
      const pathSave = path.join(pkg.version, dirParent, fileName).replace(/\\/g, '/');

      console.log(`UPLOADING ${pathSave}`);

      client.fPutObject(bucketName, pathSave, fileRaw, metaData).then(() => {
        console.log(`SUCCESS ${fileName}`);
      }).catch((err) => {
        console.log('ERROR', err);
      });
    });
  });
