const exec = require('child_process').exec
const express = require('express')
const fs = require('fs')
const app = express()
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
let isLocking = false
let logfile = './gitlabWebhook.log'
var log = function (key, str) {
    fs.appendFileSync(logfile, key + ' ' + str + '\n')
}
app.post('/deploy', function (req, res) {
    console.log(req.body)
    var key = new Date().getTime() + ''
    if (req.body.commits) {
        req.body.commits.forEach(c => {           
            log(key, c.timestamp + ' ' + c.message.trim())
        });
    }
    let headers = req.headers
    let cmdStr = 'git -c core.sshCommand="ssh -i ~/.ssh/key" pull && cnpm run build && docker cp dist/./ 9a:/var/www/html'
    //let cmdStr = 'git -c core.sshCommand="ssh -i ~/.ssh/key" pull '
    if (!isLocking && headers['x-gitlab-token'] === 'xxx') {
        isLocking = true
        exec(cmdStr, function (err, stdout, stderr) {
            if (err) {
                console.log('error:' + stderr);
                log(key, 'error:' + stderr)
            } else {
                console.log(stdout)
                log(key, 'success')
                isLocking = false
            }
        })
    }
    res.json({})
})

app.listen(8010, '0.0.0.0', function () {
    console.log(`listening on port 8010`)
})