let shell = require('shelljs')
let name = process.argv[2] || 'Auto-commit';
let exec = shell.exec;

let JSZip = require('jszip');
const path = require('path')
const fs = require('fs-extra');
const { readdirSync, readFileSync } = require('fs');


const pjson = require('./package.json');

const packageDir = `dist/${pjson.version}/${process.env.NODE_ENV}`
console.log(packageDir)

if (shell.test('-d', packageDir)) {
    shell.rm('-rf', `${packageDir}/*`)
} else {
    shell.mkdir('-p', packageDir)
}
shell.rm('-rf', 'package/')

shell.rm('-rf', ['./dist/*.dmg', './dist/*.exe', './dist/*.zip', './dist/*.yml', './dist/*.blockmap'])

if (exec('npm run package-mac').code !== 0) {
    shell.echo('Error: package-mac failed')
    shell.exit(1)
} else {
    shell.echo('-e', "\033[32m package-mac successful \033[0m")
}

if (exec('npm run package-windows').code !== 0) {
    shell.echo('Error: package-windows failed')
    shell.exit(1)
} else {
    shell.echo('-e', "\033[32m package-windows successful \033[0m")
}

shell.mv(['./dist/*.dmg', './dist/*.exe', './dist/*.zip', './dist/*.yml'], `${packageDir}/`)

createZip();

shell.echo('-e', "\033[32m 打包成功~~~~~~~~~~ \033[0m")

// if (exec('git add .').code !== 0) {
//     shell.echo('Error: Git add failed')
//     shell.exit(1)
// }
// if (exec(`git commit -am "${name}"`).code !== 0) {
//     shell.echo('Error: Git commit failed')
//     shell.exit(1)
// }
// if (exec('git push').code !== 0) {
//     shell.echo('Error: Git commit failed')
//     shell.exit(1)
// }

shell.echo('-e', "\033[32m 已提交~~~~~~~~~~ \033[0m");

function exclude(name) {
    return !['.git', '.DS_Store'].includes(name)
}

function createZip() {
    console.log('开始打zip包-------------')
    var zip = new JSZip();
    const name = process.env.NODE_ENV == 'test' ? '测试包' : '正式包';
    const target = path.join(__dirname, `/${packageDir}`);
    const output = path.join(__dirname, `/${packageDir}/边写边搜客户端-${pjson.version}${name}.zip`);
    const files = readdirSync(target);

    //遍历检测目录中的文件
    files.filter(exclude).forEach((fileName, index) => {
        // 当前文件的全路径
        let fillPath = path.join(target, fileName)

        // 获取一个文件的属性
        let file = fs.statSync(fillPath) 
        if (!file.isDirectory()) {
            // 压缩目录添加文件
            zip.file(fileName, readFileSync(fillPath)) 
        }
    })

    zip.generateAsync({type: "nodebuffer"}).then(function(content) {
        fs.outputFile(output, content)

        console.log('zip包位置：', output)
    });
}