import Client from 'ssh2-sftp-client';
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 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(() => {
    console.log("item.path", item.path);
    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();
    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();