var http = require('http')
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
var server = http.createServer(app);
const util = require('util');
const exec = util.promisify(require('child_process').exec);
var path = require("path");
app.post("/upline", async function (req, res, next) {
    console.log(req.body, "...........................")
    let version = null
    if (req.body && req.body.push_data) {
        version = req.body.push_data.tag
    }
    let containerName
    if (version) {
        try {
            let ssp = "./config/version2yaml"
            let pstr = require.resolve(ssp)
            if (require.cache[pstr]) {
                delete require.cache[pstr]
            }
            const mapfile = require(ssp)
            let endindex = version.lastIndexOf(".")
            let mapkey = version.substring(0, endindex)
            console.log(mapkey, "yaml file mapkey.......................")
            let filenameinfo = mapfile[mapkey]
            console.log(filenameinfo, "yaml file location.......................")
            let fis = filenameinfo.split("|")
            let containerName = fis[0]
            let filename = fis[1]
            let stockname = fis[2] ? fis[2] : "imgshare"
            let filepath = path.resolve(__dirname, filename)
            let patternstr
            if (filename.indexOf("jobs") > 0)
                patternstr = `kubectl set image  -f  ${filepath}   ${containerName}=registry.cn-beijing.aliyuncs.com/hantang2/${stockname}:${version}`
            else {
                let spacename = filename.indexOf("newtime") > 0 ? "newtime" : "chaolai"
                patternstr = `kubectl set image deploy ${containerName} -n ${spacename}  ${containerName}=registry.cn-beijing.aliyuncs.com/hantang2/${stockname}:${version}`
            }
            console.log(patternstr)

            let {stdout, stderr} = await exec(patternstr)
            console.log('stdout:', stdout);
            console.error('stderr:', stderr);
            pushDing(`发布成功：${containerName}-${version}`)
        } catch (e) {
            console.log(e)
            pushDing(`发布失败：${containerName}-${version}`)
            res.end("ok")
        }
    }
    res.end("ok")
})

async function pushDing(content) {
    let t = new Date().toLocaleString()
    let url = "https://oapi.dingtalk.com/robot/send?access_token=2160717973e87b0e77b23db1e656e0af01f79fd031ad9fc0adcd90c2b0d2c623"
    let curlStr = `curl -k -H 'Content-type: application/json' -d '{ "msgtype": "text","text": {"content": "${t + content}"}}' ${url}`
    let {stdout, stderr} = await exec(curlStr)
    console.log('stdout:', stdout);
    console.error('stderr:', stderr);
}

server.listen(31199, function () {
    console.log('Express server listening .....');
});