const { removeDir, copyDir, fix2 } = require('./utils');
const compressing = require('compressing');
let fs = require('fs');

async function main() {
  await removeDir('./publish/android');
  await copyDir('../play/build_android/jsb-link/remote', './publish/android');
  await removeDir('../play/build_android/jsb-link');

  const bundleData = {
    ios: await getBundleData('./publish/ios'),
    android: await getBundleData('./publish/android'),
  }

  fs.writeFileSync('./publish/config.json', JSON.stringify(bundleData));

  const tarStream = new compressing.zip.Stream();
  tarStream.addEntry('./publish/play');
  tarStream.addEntry('./publish/form');
  tarStream.addEntry('./publish/ios');
  tarStream.addEntry('./publish/android');
  tarStream.addEntry('./publish/config.json');

  const destStream = fs.createWriteStream(`publish/${getReleaseFileName()}.zip`);

  tarStream.pipe(destStream);

  console.log('打包完成！');
}

async function getBundleData(path) {
  const bundleData = {
    sceneName: '',
    version: '',
  }
  const paths = fs.readdirSync(path);
  bundleData.sceneName = paths[0];
  const files = fs.readdirSync(path + '/' + bundleData.sceneName);
  files.forEach(fileName => {
    fileName.split('.').forEach((str, idx, arr) => {
      if (str == 'config') {
        bundleData.version = arr[idx + 1];
      }
    })
  });
  return bundleData;
}

function getReleaseFileName() {
  let date = new Date();
  let fileName = `Release_${date.getFullYear()}${fix2(date.getMonth() + 1)}${fix2(date.getDate())} `;
  fileName += `${fix2(date.getHours())}-${fix2(date.getMinutes())}-${fix2(date.getSeconds())}`;
  return fileName;
}

main();