let fs = require('fs');
const compressing = require('compressing');

function fix2(num) {
    if (num >= 10) {
        return '' + num;
    } else {
        return '0' + num;
    }
}

async function initFiles() {
    const formExists = await fs.existsSync('./publish/form');
    if (formExists) {
        await fs.rmdirSync('./publish/form');
    }
}

async function copyDir(src, dst) {
    // fs.fileex
    const exists = await fs.existsSync(dst);
    if (!exists) {
        await fs.mkdirSync(dst);
    }
    //读取目录
    const paths = await fs.readdirSync(src);
    paths.forEach(async function (path) {
        const newSrc = `${src}/${path}`;
        const newDst = `${dst}/${path}`;
        const st = await fs.statSync(newSrc);
        if (st.isFile()) {
            console.log('copy ' + newDst);
            const data = await fs.readFileSync(newSrc);
            await fs.writeFileSync(newDst, data);
        } else if (st.isDirectory()) {
            copyDir(newSrc, newDst);
        }
    });
}

async function main() {
    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())}`;

    await copyDir('../play/build/web-desktop', './publish/play');

    const data = await fs.readFileSync('./index.html');
    await fs.writeFileSync('./publish/play/index.html', data);

    compressing.zip.uncompress('../form/publish/form.zip', './publish/form')
        .then(() => {
            const tarStream = new compressing.zip.Stream();
            tarStream.addEntry('./publish/play');
            tarStream.addEntry('./publish/form');

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

            tarStream.pipe(destStream);

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

main();