const shell = require('shelljs')
const path = require('path');
const config = {
  ip: "192.168.3.108", // ssh地址
  username: "root", // ssh 用户名
  port: 22,      //端口
  password: "123456", // ssh 密码
  path: '/home/itsm/project/html', // 上传地址,删除地址
  buildPath: '../dist/pc' // 本地打包后文件地址
}
let Client = require('ssh2-sftp-client');

function connectSSh() {
  let sftp = new Client();
  sftp.connect({
    host: config.ip,
    port: config.port,
    username: config.username,
    password: config.password
  }).then(() => {
    console.log("-----先执行删除服务器文件-----")
    return sftp.rmdir(config.path, true);
  }).then(() => {
    // 上传文件
    console.log("-----开始上传-----")
    return sftp.uploadDir(path.resolve(__dirname, config.buildPath), config.path);
  }).then((data) => {
    console.log("-----上传完成-----");
    sftp.end();
  }).catch((err) => {
    console.log(err, '-----失败-----');
    sftp.end();
  });
}
function runTask() {
  //打包完成
  console.log(`当前NodeJs版本是${process.version}`);
  const isNodeVersionLt17 = parseInt(process.version.slice(1)) < 17;
  const execStr = isNodeVersionLt17 ? 'npm run build' : 'npm run build:17';
  if (shell.exec(execStr).code == 0) {
    // if (shell.exec(`find dist -name '*.js' -print0 | xargs -0 gzip -k`).code == 0) {
      // if (shell.exec(`find dist -name '*.css' -print0 | xargs -0 gzip -k`).code == 0) {
        console.log("-----打包成功-----");
        //提交上传
        connectSSh();
      // }
    // }
  }
}
runTask()
