/*
 * @Author: 莫靓仔
 * @description: 文件描述
 * @Date: 2021-09-02 11:13:07
 * @LastEditors: 莫靓仔
 * @LastEditTime: 2021-09-03 20:00:51
 */
const os = require('os')
const ssh2 = require('ssh2')
const sshconfig = require('./scp/envload.js')
// const ora = require('ora')
const chalk = require('chalk')
console.log(chalk.blue('正在发布到【' + sshconfig.name + '】服务器...'))

// var ProgressBar = require('progress')
// var bar = new ProgressBar(':bar :current/:total', { total: 10 });
// var timer = setInterval(function () {
//   bar.tick();
//   if (bar.complete) {
//     clearInterval(timer);
//   } else if (bar.curr === 5) {
//       bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total);
//   }
// }, 1000);
// const spinner = ora('正在发布到' + sshconfig.name + '服务器...')

let conn = new ssh2.Client()
let url = 'sycloud'
if (sshconfig.name === '新开发环境' || sshconfig.name === '新测试环境') {
    url = 'sycloudv2'
}
// 上传
// spinner.start()

//针对MACOS 系统做处理调用本地scp命令
if (sshconfig.localScp == 1) {
    macosScp().then(
        function (data) {
            console.log(chalk.green('\n', 'sshpass成功', '\n'))
            connect(remoteCommand)
        },
        function (reason) {
            console.log(chalk.red('\n', 'sshpass失败,失败原因：', reason, '\n'))
            error()
        }
    )
} else {
    connect(uploadStart)
}

function macosScp() {
    let p = new Promise(function (resolve, reject) {
        const process = require('child_process')
        const cmd = `sshpass -p ${sshconfig.password} scp  ./ci_scp/tmp/dist.tar.gz ${sshconfig.username}@${sshconfig.host}:/opt/w/${url}/tmp/${sshconfig.app}_dist.tar.gz`
        process.exec(cmd, function (error, stdout, stderr) {
            let b = true
            if (error) {
                b = false
                reject(error)
            }
            if (stdout) {
                b = false
                resolve(stdout)
            }
            if (b) resolve('scp success!')
        })
    })
    return p
}

// 上传操作
function connect(callback) {
    conn.on('ready', () => {
        callback()
    }).connect({
        host: sshconfig.host,
        port: sshconfig.port,
        username: sshconfig.username,
        password: sshconfig.password
    })
}

function uploadStart() {
    conn.sftp((err, sftp) => {
        if (err) {
            error()
            throw err
        }
        let targetPackage = './config/tmp/dist.tar.gz'
        let serverPackage = `/opt/w/${url}/tmp/${sshconfig.app}_dist.tar.gz`
        if (os.type() == 'Windows_NT') {
            targetPackage = './config/tmp/dist.zip'
            serverPackage = `/opt/w/${url}/tmp/${sshconfig.app}_dist.zip`
        }
        sftp.fastPut(targetPackage, serverPackage, {}, (err, result) => {
            if (err) {
                error()
                throw err
            }
            //上传完成后开始解压
            remoteCommand()
        })
    })
}

// 解压部署操作
function remoteCommand() {
    conn.shell((err, stream) => {
        if (err) {
            error()
            throw err
        }
        let scpCommand = `
            cd /opt/w/${url}/
            rm -rf ${sshconfig.app}_backup.tar.gz
            tar -zcf ${sshconfig.app}_backup.tar.gz ${sshconfig.app}/
            rm -rf ${sshconfig.app}
            mv /opt/w/${url}/tmp/${sshconfig.app}_dist.tar.gz dist.tar.gz
            tar -zxf dist.tar.gz
            rm -rf dist.tar.gz
            exit
        `
        if (os.type() == 'Windows_NT') {
            scpCommand = `
                cd /opt/w/${url}/
                rm -rf ${sshconfig.app}_backup.tar.gz
                tar -zcf ${sshconfig.app}_backup.tar.gz ${sshconfig.app}/
                rm -rf ${sshconfig.app}
                mv /opt/w/${url}/tmp/${sshconfig.app}_dist.zip dist.zip
                unzip dist.zip
                rm -rf dist.zip
                exit
            `
        }
        stream
            .end(scpCommand)
            .on('data', data => {
                //不输出日志
                //console.log(chalk.green(data.toString()))
            })
            .on('close', () => {
                conn.end()
                // spinner.stop()
                console.log(chalk.green('Success! 成功发布到【' + sshconfig.name + '【服务器! \n'))
            })
    })
}

function error() {
    // spinner.stop()
    conn.end()
    console.log(chalk.red('发布失败.\n'))
}
