package org.jeecg.modules.adweb.common.service;


import org.jeecg.modules.adweb.common.util.ShellSSH2Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * shell脚本调用
 *
 * @author jerry-
 */
@Service
public class ShellService {
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(ShellService.class);

    @Value("${adcloud.file.rootpath}")
    String rootPath;
    @Value("${admp.shell.path}")
    private String shellPath;
    @Value("${jumpServer.pulicIp}")
    private String pulicIp;
    @Value("${jumpServer.username}")
    private String jumpServerUserName;
    @Value("${jumpServer.pem}")
    private String jumpServerPem;

    @Value("${usWest118Server.ip}")
    private String usWest118ServerIp;

    @Value("${usWest118Server.username}")
    private String usWest118ServerUsername;

    @Value("${usWest118Server.pem}")
    private String usWest118ServerPem;

    @Value("${usWest118Server.port}")
    private Integer usWest118ServerPort;

    @Value("${usWest118Server.shellpath}")
    private String usWest118ServerShellPath;

    @Value("${v2.projectPath}")
    private String v2ProjectPath;

    /**
     * 创建共享站点  命令
     *
     * @param cmd            控制台返回监听器
     * @param host           建站连接测试环境配置 域名
     * @param port           端口
     * @param username
     * @param password
     * @param stdoutListener
     */
    public void createShareSiteByPwd(String cmd
            , String host
            , int port
            , String username
            , String password
            , ShellSSH2Util.StdoutListener stdoutListener) {
        exceShellByPwd(cmd, host, port, username, password, stdoutListener);
    }


    /**
     * 执行远程Shell脚本 (通过用户名和密码)
     *
     * @param cmd            命令
     * @param host           建站连接测试环境配置 域名
     * @param port           端口
     * @param username
     * @param password
     * @param stdoutListener
     * @param stdoutListener 控制台输出监听器
     */
    public void exceShellByPwd(String cmd
            , String host
            , int port
            , String username
            , String password
            , ShellSSH2Util.StdoutListener stdoutListener) {
        long currentTimeMillis = System.currentTimeMillis();
        ShellSSH2Util.execmdByPwd(host, port, username, password, cmd, stdoutListener);
        long currentTimeMillis1 = System.currentTimeMillis();
        logger.info("花费时间：" + (currentTimeMillis1 - currentTimeMillis));
    }

    /**
     * 站点发布
     *
     * @param domain
     * @param code
     * @return
     */
    public Integer publishSiteShell(String domain, String code) {
        logger.info("发布域名:{},站点code:{}", domain, code);
        String cmd = shellPath + "adweb2.0-website.sh " + domain + " " + code;
        logger.info("脚本命令:{}", cmd);
        Process p;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }

    /**
     * 子站点发布
     *
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public Integer publishChildrenSiteShell(String sourcePath, String targetPath) {
        logger.info("源站点:{},目标位置:{}", sourcePath, targetPath);
        String cmd = shellPath + "createChildSiteLink.sh " + sourcePath + " " + targetPath;
        logger.info("脚本命令:{}", cmd);
        Process p = null;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }

    /**
     * @param targetPath
     * @return
     */
    public Integer rmChildrenSiteShell(String targetPath) {
        logger.info("目标位置:{}", targetPath);
        String cmd = shellPath + "rmChildSiteLink.sh " + targetPath;
        logger.info("脚本命令:{}", cmd);
        Process p = null;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }

    /**
     * @param domain
     * @return
     */
    public Integer stopSiteShell(String domain) {
        logger.info("源站点:{}", domain);
        String cmd = shellPath + "stop_site.sh " + domain;
        logger.info("脚本命令:{}", cmd);
        Process p = null;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }

    /**
     * @param domain
     * @return
     */
    public Integer startSiteShell(String domain) {
        logger.info("源站点:{}", domain);
        String cmd = shellPath + "start_site.sh " + domain;
        logger.info("脚本命令:{}", cmd);
        Process p = null;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }

    /**
     * @param siteCode
     * @return
     */
    public Integer createSiteSsl(String siteCode) {
        logger.info("源站点:{}", siteCode);
        String cmd = shellPath + "stopSite.sh " + siteCode;
        logger.info("脚本命令:{}", cmd);
        Process p = null;
        int res = 0;
        try {
            p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if ("finished".equals(line)) {
                    res = 1;
                }
                logger.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            res = 0;
        }
        return res;
    }


    /**
     * 执行远程Shell脚本
     *
     * @param cmd            命令
     * @param stdoutListener 控制台输出监听器
     */
    public void exceShell(String cmd, ShellSSH2Util.StdoutListener stdoutListener) {
        long currentTimeMillis = System.currentTimeMillis();
        File pemFile = new File(jumpServerPem);
        ShellSSH2Util.execmd(pulicIp, jumpServerUserName, pemFile, cmd, stdoutListener);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("花费时间：" + (currentTimeMillis1 - currentTimeMillis));
    }

    /**
     * 执行远程Shell脚本
     *
     * @param cmd            命令
     * @param stdoutListener 控制台输出监听器
     */
    public void exceShellByUsWest118(String cmd, ShellSSH2Util.StdoutListener stdoutListener) {
        long currentTimeMillis = System.currentTimeMillis();
        File pemFile = new File(usWest118ServerPem);
        ShellSSH2Util.execmd(usWest118ServerIp, usWest118ServerPort, usWest118ServerUsername, pemFile, cmd, stdoutListener);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("花费时间：" + (currentTimeMillis1 - currentTimeMillis));
    }

    /**
     * 执行远程Shell脚本
     *
     * @param cmd            命令
     * @param stdoutListener 控制台输出监听器
     */
    public void exceShellByServerInfo(String cmd, String ip, Integer port, String username, String password, ShellSSH2Util.StdoutListener stdoutListener) {
        long currentTimeMillis = System.currentTimeMillis();
        if (password.contains(".cer") || password.contains(".pem")) {
            File pemFile = new File(v2ProjectPath + "/" + password);
            ShellSSH2Util.execmd(ip, port, username, pemFile, cmd, stdoutListener);
        } else {
            ShellSSH2Util.execmdByPwd(ip, port, username, password, cmd, stdoutListener);
        }
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("花费时间：" + (currentTimeMillis1 - currentTimeMillis));
    }
}
