package cn.reghao.bnt.deployer;

import cn.reghao.bnt.deployer.model.RemoteHost;
import cn.reghao.bnt.deployer.util.Sftp;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * @author reghao
 * @date 2024-02-19 14:16:27
 */
@Slf4j
public class DeployApp {
    public static void main(String[] args) {
        if (args.length != 4) {
            log.error("usage: java -jar devops-deployer ${app_name} ${local_dir} ${remote_dir} ${sever_file}");
            return;
        }

        String appName = args[0];
        String localDir = args[1];
        File file1 = new File(localDir);
        if (!file1.exists() || file1.isFile()) {
            log.error("local_dir {} is not exist or is a file", localDir);
            return;
        }

        String remoteDir = args[2];
        String serverFile = args[3];
        File file2 = new File(serverFile);
        if (!file2.exists() || file2.isDirectory()) {
            log.error("server_file {} is not exist or is a directory", serverFile);
            return;
        }

        log.info("start deploy devops apps");
        Sftp sftp = new Sftp();
        List<RemoteHost> remoteHosts = sftp.getRemoteHost(serverFile);
        for (RemoteHost remoteHost : remoteHosts) {
            try {
                String host = remoteHost.getHost();
                sftp.deploy(localDir, remoteDir, remoteHost);
                log.info("deploy {} on {} done", appName, host);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("deploy devops done");
    }
}
