#!/bin/bash

SCRIPT_PATH=$(cd $(dirname $0);pwd)
SELF_FILE=$(basename $0)


modify_nic_glb()
{
    if [[ ${src_version} == "r21c10" ]];then
        (
cat <<EOF
#!/usr/bin/env python3
# encoding: utf-8
"""回退前删除odaedatacatalogdb中多余的索引"""

import os
import sys
import subprocess
import json
import logging
import pyzenith
from deployment import containerlist
from deployment import tenants
from util import ossext

SUCCESS = 0
FAILED = 1
SYSMGR_DB = "sysmgrdb"
LOG_FILE = os.path.splitext(os.path.realpath(__file__))[0] + '.log'
logging.basicConfig(filename=LOG_FILE, level=logging.INFO,
                    format=' %(asctime)s - %(levelname)s - %(message)s')


def modify_nic(master_instance_dict):
    """
    升级环境修改网卡用途
    :return:
    """
    print("Start to modify nic")
    key = ''
    for instance_key in master_instance_dict.keys():
        if "managedbsvr" in instance_key:
            key = instance_key
            break
    if not master_instance_dict.get(key):
        print("query instance name failed")
        logging.error("query instance name failed")
        return
    db_info_dict = master_instance_dict.get(key)
    connect_ip = db_info_dict.get("connect_ip")
    port = db_info_dict.get("port")
    db_info = db_info_dict.get("db_list").get(SYSMGR_DB)
    if not db_info:
        log_info = "no such database: {}".format(SYSMGR_DB)
        print(log_info)
        logging.error(log_info)
        return
    print(f"master:{connect_ip}")
    password = ossext.Cipher.decrypt(db_info.get("dbUserPasswd"))
    conn = pyzenith.connect(host=connect_ip, user=SYSMGR_DB,
                            passwd=password, port=str(port))
    cursor = conn.cursor()
    modify_maintenance_ip_nic(conn, cursor)
    cursor.close()
    conn.close()
    print("End to modify nic")
    return


def modify_maintenance_ip_nic(conn, cursor):
    """
     修改网卡用途
    :param conn:
    :param cursor:
    :return:
    """
    analyzer_main_ips = get_analyzer_info()
    if not analyzer_main_ips:
        print("analyzer main ips get failed")
        logging.error("analyzer main ips get failed")
        return

    ips_list = []
    for node_value in analyzer_main_ips:
        for ip_item in node_value.get("IPAddresses", []):
            now_ip = ip_item.get("IP", "")
            if "maintenance" in ip_item.get("usage", []):
                ips_list.append(now_ip)
    print(ips_list)
    try:
        for ip_info in ips_list:
            query_sql = f"select USAGES, RESERVED13 from " \
                        f"tbl_ip_address where ip_address = '{ip_info}'"
            cursor.execute(query_sql)
            query_info = cursor.fetchall()
            for info in query_info:
                exe_sql(cursor, info, ip_info)
    except pyzenith.DatabaseError:
        log_info = "execute sql failed"
        print(log_info)
        logging.debug(log_info)
        return
    conn.commit()
    return


def exe_sql(cursor, info, ip_info):
    """
    执行sql
    """
    if "ODAE-AP-IP" not in info[0]:
        print(info)
        usages = info[0] + ",ODAE-AP-IP"
        reserved = info[1] + ":ODAE-AP-IP"
        update_sql = f"update tbl_ip_address set USAGES = '{usages}'," \
                     f"RESERVED13 = '{reserved}' where ip_address = '{ip_info}'"
        cursor.execute(update_sql)


def get_analyzer_info():
    """
    获取分析器节点信息
    """
    node_lists_path = os.path.join(os.environ['INSTALL_ROOT'],
                                   "manager/etc/sysconf/nodelists.json")
    with open(node_lists_path, 'r') as nodelists_file:
        node_list_json = json.load(nodelists_file)
    node_list = node_list_json.get("nodeList", {})
    node_values = []
    for _, node_value in node_list.items():
        if "Collector" not in node_value["hostname"]:
            node_values.append(node_value)
    return node_values


def get_master_db_instance():
    """
    获取当前节点所有主数据库实例
    :return:
    """
    all_instance_list = containerlist.ContainerList(tenants.Tenant("manager")) \
        .get_dc_by_type_list("zenith")

    master_instance_dict = {}
    command = "{path}/manager/apps/DBAgent/bin/dbsvc_adm -cmd query-db-instance | " \
              "grep {cluster_name} | grep \" {ip} \" | grep Master"
    for instance in all_instance_list:
        if not instance.get_cluster_name():
            cluster_name = instance.get_name()
        else:
            cluster_name = instance.get_cluster_name()
        status, _ = subprocess.getstatusoutput(command.format(
            path=os.environ['INSTALL_ROOT'], cluster_name=cluster_name, ip=instance.get_ip()))
        if status == SUCCESS:
            get_db_list(all_instance_list, instance, master_instance_dict)

    return master_instance_dict


def get_db_list(all_instance_list, instance, master_instance_dict):
    """
    获取dblist信息
    """
    db_list = instance.get_db_list()
    if not db_list:
        log_info = "no db_list in {}".format(instance.get_name())
        print(log_info)
        logging.debug(log_info)
        for peer_instance in all_instance_list:
            if peer_instance.get_name().split("-")[0] == instance.get_name().split("-")[0] \
                    and peer_instance != instance:
                db_list = peer_instance.get_db_list()
                log_info = "get db_list in {}".format(peer_instance.get_name())
                print(log_info)
                logging.debug(log_info)
    if not db_list:
        log_info = "db_list is null,please confirm"
        print(log_info)
        logging.error(log_info)
        return
    master_instance_dict[instance.get_name()] = {
        "connect_ip": instance.get_ip(),
        "port": instance.get_port(),
        "db_list": db_list
    }


def main():
    """
    函数入口
    :return:
    """
    master_instance_dict = get_master_db_instance()
    if not master_instance_dict:
        log_info = "current node has no master instance,exit 0"
        print(log_info)
        logging.debug(log_info)
        return FAILED

    modify_nic(master_instance_dict)
    return SUCCESS


if __name__ == '__main__':
    sys.exit(main())

EOF
        ) > /tmp/modify_nic_glb.py
    else
        (
cat <<EOF
#!/usr/bin/env python3
# encoding: utf-8
"""回退前删除odaedatacatalogdb中多余的索引"""

import os
import sys
import subprocess
import json
import logging
import pyzenith
from deployment import containerlist
from deployment import tenants
from util import ossext

SUCCESS = 0
FAILED = 1
SYSMGR_DB = "sysmgrdb"
LOG_FILE = os.path.splitext(os.path.realpath(__file__))[0] + '.log'
logging.basicConfig(filename=LOG_FILE, level=logging.INFO,
                    format=' %(asctime)s - %(levelname)s - %(message)s')


def modify_nic(master_instance_dict):
    """
    升级环境修改网卡用途
    :return:
    """
    print("Start to modify nic")
    key = ''
    for instance_key in master_instance_dict.keys():
        if "managedbsvr" in instance_key:
            key = instance_key
            break
    if not master_instance_dict.get(key):
        print("query instance name failed")
        logging.error("query instance name failed")
        return
    db_info_dict = master_instance_dict.get(key)
    connect_ip = db_info_dict.get("connect_ip")
    port = db_info_dict.get("port")
    db_info = db_info_dict.get("db_list").get(SYSMGR_DB)
    if not db_info:
        log_info = "no such database: {}".format(SYSMGR_DB)
        print(log_info)
        logging.error(log_info)
        return
    print(f"master:{connect_ip}")
    password = ossext.Cipher.decrypt(db_info.get("dbUserPasswd"))
    conn = pyzenith.connect(host=connect_ip, user=SYSMGR_DB,
                            passwd=password, port=str(port))
    cursor = conn.cursor()
    modify_maintenance_ip_nic(conn, cursor)
    cursor.close()
    conn.close()
    print("End to modify nic")
    return


def modify_maintenance_ip_nic(conn, cursor):
    """
     修改网卡用途
    :param conn:
    :param cursor:
    :return:
    """
    analyzer_main_ips = get_analyzer_info()
    if not analyzer_main_ips:
        print("analyzer main ips get failed")
        logging.error("analyzer main ips get failed")
        return

    ips_list = []
    for node_value in analyzer_main_ips:
        for ip_item in node_value.get("IPAddresses", []):
            now_ip = ip_item.get("IP", "")
            if "maintenance" in ip_item.get("usage", []):
                ips_list.append(now_ip)
    print(ips_list)
    try:
        for ip_info in ips_list:
            query_sql = f"select USAGES, RESERVED13 from " \
                        f"tbl_ip_address where ip_address = '{ip_info}'"
            cursor.execute(query_sql)
            query_info = cursor.fetchall()
            for info in query_info:
                if "ODAE-AP-IP" not in info[0]:
                    print(info)
                    usages = info[0] + ",ODAE-AP-IP"
                    reserved = info[1] + ":ODAE-AP-IP"
                    update_sql = f"update tbl_ip_address set USAGES = '{usages}'," \
                                 f"RESERVED13 = '{reserved}' where ip_address = '{ip_info}'"
                    cursor.execute(update_sql)
    except pyzenith.DatabaseError:
        log_info = "execute sql failed"
        print(log_info)
        logging.debug(log_info)
        return
    conn.commit()
    return


def get_analyzer_info():
    """
    获取分析器节点信息
    """
    node_lists_path = os.path.join(os.environ['INSTALL_ROOT'],
                                   "manager/etc/sysconf/nodelists.json")
    with open(node_lists_path, 'r') as nodelists_file:
        node_list_json = json.load(nodelists_file)
    node_list = node_list_json.get("nodeList", {})
    node_values = []
    for _, node_value in node_list.items():
        ext_attr = node_value.get("extAttr", {})
        ptp_level = ext_attr.get("ptpLevel", None)
        if not ptp_level:
            node_values.append(node_value)
    return node_values


def query_product_name():
    """
    查询产品名称
    :return:
    """
    query_cmd = "ls /opt/oss/log | grep -v manager | grep -v NCE | grep -v ICMR"
    status, output = subprocess.getstatusoutput(query_cmd)
    if status != SUCCESS:
        log_info = "query product name failed"
        print(log_info)
        logging.error(log_info)
        sys.exit(FAILED)
    return output.replace("\n", "").replace("\r", "")


def get_master_db_instance():
    """
    获取当前节点所有主数据库实例
    :return:
    """
    all_instance_list = containerlist.ContainerList(tenants.Tenant("manager")) \
        .getDCByTypeList("zenith")

    master_instance_dict = {}
    command = "{path}/manager/apps/DBAgent/bin/dbsvc_adm -cmd query-db-instance | " \
              "grep {cluster_name} | grep \" {ip} \" | grep Master"
    for instance in all_instance_list:
        if not instance.getClusterName():
            cluster_name = instance.getName()
        else:
            cluster_name = instance.getClusterName()
        status, _ = subprocess.getstatusoutput(command.format(
            path=os.environ['INSTALL_ROOT'], cluster_name=cluster_name, ip=instance.getIP()))
        if status == SUCCESS:
            db_list = instance.getDBList()
            if not db_list:
                log_info = "no db_list in {}".format(instance.getName())
                print(log_info)
                logging.debug(log_info)
                for peer_instance in all_instance_list:
                    if peer_instance.getName().split("-")[0] == instance.getName().split("-")[0] \
                            and peer_instance != instance:
                        db_list = peer_instance.getDBList()
                        log_info = "get db_list in {}".format(peer_instance.getName())
                        print(log_info)
                        logging.debug(log_info)
            if not db_list:
                log_info = "db_list is null,please confirm"
                print(log_info)
                logging.error(log_info)
                sys.exit(FAILED)
            master_instance_dict[instance.getName()] = {
                "connect_ip": instance.getIP(),
                "port": instance.getPort(),
                "db_list": db_list
            }

    log_info = "master_instance_dict:  {}".format(master_instance_dict)
    return master_instance_dict


def main():
    """
    函数入口
    :return:
    """
    master_instance_dict = get_master_db_instance()
    if not master_instance_dict:
        log_info = "current node has no master instance,exit 0"
        print(log_info)
        logging.debug(log_info)
        sys.exit(SUCCESS)

    modify_nic(master_instance_dict)
    sys.exit(SUCCESS)


if __name__ == '__main__':
    main()

EOF
        ) > /tmp/modify_nic_glb.py
    fi

    chown ossadm:ossgroup /tmp/modify_nic_glb.py
    chmod 500 /tmp/modify_nic_glb.py
    su - ossadm -c 'source /opt/oss/manager/bin/engr_profile.sh;python /tmp/modify_nic_glb.py' >> /tmp/modify_nic_glb.log
    local result=$?
    rm -rf /tmp/modify_nic_glb.py
    return $result
}


main()
{
    logger  -p local0.info "user: `who -m | cut -d\( -f2 |cut -d\) -f1`, execute ${SELF_FILE} begin."
    src_version=$1
    version_array=("r21c00", "r21c10")
    if [[ ! "${version_array[@]}" =~ "${src_version}" ]];then
        echo "not support params" >> /tmp/modify_nic_glb.log
        return 1
    fi
    modify_nic_glb || exit 1
    logger  -p local0.info "user: `who -m | cut -d\( -f2 |cut -d\) -f1`, execute ${SELF_FILE} success."
}

main "$@"