package com.yutou.nas.Controllers;

import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.utils.RedisTools;
import com.yutou.nas.utils.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class UpdateIp {
    private static List<String> keys = new ArrayList<>();
    public static String nas_ip=null;
   /* static {
        keys.add("nas.yutou233.cn;");
        keys.add("bt.yutou233.cn;");
        keys.add("samba445-server");
        keys.add("samba139-server");
        keys.add("nas-ssh-server");
        keys.add("nas-ftp-server");
    }*/


    @RequestMapping("/nas/updateip.do")
    public void updateIp(String ip) {

        updateList();
        File file = new File("/etc/nginx/nginx.conf");
        if (file.exists()) {
            com.yutou.nas.utils.Log.i("文件存在，修改 ip>" + ip);
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                StringBuilder stringBuffer = new StringBuilder();
                String line = null;
                boolean isIp = false;
                boolean isNas=false;
                nas_ip=ip;
                while ((line = reader.readLine()) != null) {
                    //com.yutou.nas.utils.Log.i(line.trim().replace("server_name","").replace("upstream","").trim());
                    if (keys.contains(line.trim().replace("server_name", "").replace("upstream", "").replace("{", "").trim())) {
                        isIp = true;
                    }
                    if(line.trim().replace("server_name", "").trim().equals("nas.yutou233.cn;")){
                        isNas=true;
                    }
                    if (isIp) {
                        String testIp = testIp(line);
                        if (testIp != null) {
                            com.yutou.nas.utils.Log.i("检测到目标：" + line + " 修改IP " + testIp + " > " + ip);
                            if(isNas){
                                String adminAddress= RedisTools.get("adminAddress");
                                if(adminAddress!=null) {
                                    JSONObject json=JSONObject.parseObject(adminAddress);
                                    line = "proxy_pass http://" +ip+":"+json.getInteger("port")+"/;";
                                }else{
                                    line = line.replace(testIp, ip);
                                }
                                isNas=false;
                            }else {
                                line = line.replace(testIp, ip);
                            }

                            isIp = false;
                        }
                    }
                    stringBuffer.append(line).append("\n");
                }
                reader.close();
                FileWriter writer = new FileWriter(file);
                writer.write(stringBuffer.toString());
                writer.flush();
                writer.close();
                com.yutou.nas.utils.Log.i("修改完成");
                Runtime.getRuntime().exec("nginx -s reload");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/nas/getIp.do")
    @ResponseBody
    public String getIP(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        json.put("code", -1);
        json.put("msg", "未登录");
        if (Tools.checkWebLogin(request) != 1) {
            //  return json.toJSONString();
        }
        json.put("code", 0);
        json.put("msg", "ok");
        json.put("data", nas_ip);
        return json.toJSONString();
    }

    public String testIp(String ip) {
        String pattern = "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}";
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(ip);
        //  com.yutou.nas.utils.Log.i("送检测IP:"+ip);
        if (matcher.find())
            return ip.substring(matcher.start(), matcher.end());
        return null;
    }

    private void updateList() {
        File file = new File("ipconfig.txt");
        try {
            if (!file.exists()) {
                boolean create = file.createNewFile();
                if (create)
                    com.yutou.nas.utils.Log.i("创建文件完成：" + file.getAbsolutePath());
            }
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String tmp;
            while ((tmp = reader.readLine()) != null) {
                if (!keys.contains(tmp.trim()))
                    keys.add(tmp.trim());
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
    }
}
