const { execSync } = require('child_process');
const { isNullES } = require('js-fast-way')

//获取参数
const args = process.argv[2]
const serverAddress = process.argv[3]
const username = process.argv[4]
const password = process.argv[5]
const fileName = process.argv[6]
const filePath = process.argv[7]
const url = process.argv[8]

// 解析服务器地址和端口
const [serverIp, port] = serverAddress.split(':');
const sshPort = port || '22';  // 如果没有指定端口,默认使用22

// 这里填入您之前获取的主机密钥的 SHA256 指纹
//plink -ssh root@192.168.0.109 -P 22 exit
const hostKey = "SHA256:qS+DxUoW0NM1Nc//Dh0ebUHTB+MXMNTr+BF0njciwrU"

// 检查命令是否可用
function commandExists(command) {
    try {
        execSync(`which ${command}`, { stdio: 'ignore' });
        return true;
    } catch (e) {
        return false;
    }
}

// 执行命令并打印输出
function runCommand(command) {
    console.log(`执行命令: ${command}`);
    try {
        if (command.startsWith('sshpass') || command.startsWith('ssh')) {
            // 为SSH命令设置LC_ALL
            command = `LC_ALL=C ${command}`;
        }
        execSync(command, { stdio: 'inherit' });
    } catch (error) {
        console.error(`命令执行失败: ${error.message}`);
        process.exit(1);
    }
}

// 上传到服务器
function uploadServer() {
    const sshCommand = `cd ${filePath} && rm -rf static && unzip -o ${fileName}`;
    if (process.platform === 'win32') {
        // Windows
        runCommand(`pscp -P ${sshPort} -pw ${password} -hostkey "${hostKey}" ./zip/${fileName} ${username}@${serverIp}:${filePath}`);
        runCommand(`plink -P ${sshPort} -ssh ${username}@${serverIp} -pw ${password} -hostkey "${hostKey}" -batch "${sshCommand}"`);
    } else {
        // Mac/Linux
        runCommand(`sshpass -p "${password}" scp -o StrictHostKeyChecking=no -P ${sshPort} ./zip/${fileName} ${username}@${serverIp}:${filePath}`);
        runCommand(`sshpass -p "${password}" ssh -o StrictHostKeyChecking=no -p ${sshPort} ${username}@${serverIp} "${sshCommand}"`);
    }
    console.log('编译打包后自动部署到服务器上完成');
    console.log(`服务器上的地址:${url}`);
}

// 删除 plugins 等目录
function delPublic() {
    console.log('准备移除 plugins 等目录');
    const sshCommand = `cd ${filePath} && rm -rf plugins`;
    if (process.platform === 'win32') {
        // Windows
        runCommand(`plink -P ${sshPort} -ssh ${username}@${serverIp} -pw ${password} -hostkey "${hostKey}" -batch "${sshCommand}"`);
    } else {
        // Mac/Linux
        runCommand(`sshpass -p "${password}" ssh -o StrictHostKeyChecking=no -p ${sshPort} ${username}@${serverIp} "${sshCommand}"`);
    }
    console.log('plugins 等目录移除完成');
}

//执行
function runCode() {
    //参数是否为空
    if (args === 'undefined' || serverIp === 'undefined' || username === 'undefined' || password === 'undefined' || fileName === 'undefined' || filePath === 'undefined') {
        console.log('参数异常,终止执行:', { args,serverIp, username, password, fileName, filePath });
        process.exit(1);
        return
    }
    if (isNullES(args) || isNullES(serverIp) || isNullES(username) || isNullES(password) || isNullES(fileName) || isNullES(filePath)) {
        console.log('参数异常,终止执行:', { args,serverIp, username, password, fileName, filePath });
        process.exit(1);
        return
    }

    //判断命令是否支持
    if (process.platform === 'win32') {
        if (!commandExists('pscp') || !commandExists('plink')) {
            console.log('putty 未安装,请先安装 putty');
            process.exit(1);
            return
        }
    } else {
        if (!commandExists('sshpass')) {
            console.log('sshpass 未安装,请先安装 sshpass');
            process.exit(1);
            return
        }
    }

    //如果是上传全部,就删除不常动的目录
    if (args === 'all') {
        delPublic();
    }
    //上传到服务器
    uploadServer();
}

runCode()