import Client from 'ssh2-sftp-client';
import ssh2 from 'ssh2';
import chalk from 'chalk';
import ora from 'ora';
import shell from 'shelljs';
import path from 'path';
import { fileURLToPath } from 'url';
import { config } from './config.js';

const rawArgv = process.argv.slice(2);
const filterStage = rawArgv.includes("--prod") ? "prod" : "test";
const __dirname = path.dirname(fileURLToPath(import.meta.url));

// 构建
const compileDist = async () => {
  console.log(chalk.blue("项目开始构建"));
  if (shell.exec(`npm run build:${filterStage}`).code === 0) {
    console.log(chalk.blue("项目构建成功"));
  }
}

// 获取配置
const getConfig = () => {
  const [result] = config.filter(({ nodeEnv }) => nodeEnv === filterStage);
  return result;
}


const execRemoteCommand = async () => {
  const config = getConfig();
  const conn = new ssh2.Client();

  conn.on("ready", function () {
    console.log(chalk.blue("ssh2 链接成功"));

    const commands = [
      'cd /data/node_web/modelAdmin',
      'pwd',
      'pm2 list',
      'pm2 del bigModelAdmin',
      'pm2 start'
    ];

    conn.exec(commands.join(";"), { pty: true }, function (err, stream) {
      if (err) throw err;
      stream
        .on('close', function (code, signal) {
          console.log('Command 执行成功');
          conn.end(); // 结束SSH连接
        })
        .on('data', function (data) {
          process.stdout.write(data);
        });

      stream.stdin.end();
    });
  }).connect({ ...config });
}

// 部署
const connectShell = async () => {
  const sftp = new Client();
  const item = getConfig();
  let spinner = null;

  // 打印信息
  const printMsg = ({ color, text }) => {
    console.log(chalk.red(`${item.host} --> `) + chalk[color](text));
  }

  printMsg({ color: 'green', text: '服务器连接中' });

  sftp.connect({
    host: item.host,
    port: item.port,
    username: item.username,
    password: item.password,
  })
    .then(() => {
      printMsg({ color: 'green', text: '服务器连接成功' });
      printMsg({ color: 'yellow', text: '执行删除文件中' });
      return sftp.rmdir(item.path, true);
    })
    .then(() => {
      printMsg({ color: 'green', text: '执行删除文件成功' });
      printMsg({ color: 'green', text: '即将开始上传' });
      spinner = ora().start();
      spinner.text = '文件上传中,请等待'
      return sftp.uploadDir(path.resolve(__dirname, "../dist"), item.path);
    })
    .then(() => {
      spinner.info('文件上传结束')
      spinner.stop();

      // if (filterStage === 'prod') {
      // execRemoteCommand()
      // }
      
      printMsg({ color: 'green', text: '部署完成' });
      // printMsg({ color: 'green', text: '上传完成,准备指令中' });
      sftp.end();
    })
    .catch((err) => {
      console.error(
        err,
        chalk.red(`${item.host} -->`) + chalk.red(`上传失败`)
      );
      sftp.end();
    });
}

async function runStart() {
  await compileDist();
  await connectShell();
}

runStart();