const path = require('path')
const { exec } = require('child_process')

const fileHandler = require('./file')

const packages = ['h5101', 'h5103', 'h5106']
let currentIndex = 0

const startPackage = (package) => {
  console.log('开始打包：', package)
  const packagePath = path.resolve(__dirname, '../')
  exec(`cd ${packagePath} && npm run build:${package}`, (error, stdout, stderr) => {
    if (error) {
      console.error(`打包出错：${package} ${error}`)
      return
    }

    if (stderr) {
      console.error('std error', stderr)
      return
    }
    // console.log('std out', stdout)

    console.log('打包成功：', package)

    const sourceDir = path.resolve(__dirname, '../dist/build/h5')
    const destinationDir = path.resolve(__dirname, `../dist/package/${package}`)

    console.log('复制文件:', sourceDir)
    console.log('目标目录:', destinationDir)
    
    fileHandler.deleteDirectory(destinationDir)
      .then(() => {
        fileHandler.copyDirectory(sourceDir, destinationDir)
          .then(() => {
            console.log('复制完成', package)

            if (currentIndex < packages.length - 1) {
              currentIndex++
              startPackage(packages[currentIndex])
            } else {
              console.log('全部打包完成')
            }
          })
          .catch(err => {
            console.error('复制过程中发生错误:', err)
          })
      }).catch(error => {
        console.error('删除文件夹时发生错误:', error)
      })
  })
}

startPackage(packages[currentIndex])
