
const co = require('co');
const OSS = require('ali-oss');
var fs = require('fs');

let arg = process.argv.splice(2);

//只打包js时，自执行上传
if(arg[0])uploadSingleJs();
function uploadSingleJs(url) {

    if (!url) {//不传的时候
        const configFileName = 'project.json';
        if (!fs.existsSync(configFileName)) {
            throw new Error(`${configFileName}不存在.`)
        }
        let config = fs.readFileSync('project.json');
        config = JSON.parse(config + '');
        if (!config.type) {
            throw new Error(`${configFileName}的type不存在.`)
        }

        if (!config.name) {
            throw new Error(`${configFileName}的name不存在.`)
        }

        const now = new Date();
        const version = Math.round(now.getTime() / 1000);
        console.log(`版本号：
        ${version}`)
        url = `${config.type}/${config.name}/${version}`;


        require("./createHtml")(`${config.type}/${config.name}/${version}`);
    }

    //单js文件上传
    co(function* () {
        const originPath = `/db_games/${url}/output.js`;
        var client = new OSS({
            region: 'oss-cn-hangzhou',
            accessKeyId: 'LTAI5tLEo6SbjfmNPmH7Mz3o',
            accessKeySecret: '8yZ6nVMg56DEupEEMRl6rz1DcpG2R7',
            bucket: 'duiba'
        })
        var originFile;
        try {
            originFile = yield client.head(originPath);
        } catch (error) {
            originFile = error;
        }
        if (originFile.status === 404)
            yield client.put(originPath, "./output.js");
    })
}

module.exports = uploadSingleJs