#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import sys
    import importlib

    importlib.reload(sys)
    import subprocess
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.os.gsnetwork import g_network
    from gspylib.os.gsplatform import g_Platform
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))

networkCardNum = ""


class CheckMTU(BaseItem):
    def __init__(self):
        super(CheckMTU, self).__init__(self.__class__.__name__)
        self.expectMTU1 = None
        self.expectMTU2 = None

    def preCheck(self):
        # check current node contains cn instances if not raise  exception
        super(CheckMTU, self).preCheck()
        # check the threshold was set correctly
        if (not self.threshold.__contains__('expectMTU1')):
            raise Exception("threshold expectMTU1 can not be empty")
        self.expectMTU1 = self.threshold['expectMTU1']
        if (not self.threshold.__contains__('expectMTU2')):
            raise Exception("threshold expectMTU2 can not be empty")
        self.expectMTU2 = self.threshold['expectMTU2']

    def doCheck(self):
        global networkCardNum
        self.ipAddr, self.service_network_adapt, self.service_network_adapts = \
            SharedFuncs.getLocalIP(self.nodes, self.all_network_info)
        networkCardNum = self.service_network_adapt.NICNum
        networkMTU = g_Platform.getNetworkMTUValueByNICNum(networkCardNum)
        if (not networkCardNum or not networkMTU):
            raise Exception("Failed to obtain network card information.")
        # Check the mtu value obtained is not a number
        if (not str(networkMTU).isdigit()):
            raise Exception("Failed to obtain network card [%s] MTU value." % networkCardNum)

        self.result.val = str(networkMTU)
        # Compare the acquired MTU with the threshold
        if (int(networkMTU) != int(self.expectMTU1) and int(networkMTU) != int(self.expectMTU2)):
            self.result.rst = ResultStatus.WARNING
            self.result.raw = "Warning MTU value[%s]: RealValue '%s' ExpectedValue '%s' or '%s'.\n" % (
                networkCardNum, int(networkMTU), self.expectMTU1, self.expectMTU2)
        else:
            self.result.rst = ResultStatus.OK
            self.result.raw = "[%s]MTU: %s" % (networkCardNum, str(networkMTU))

    def doSet(self):
        resultStr = ""
        (_, initFile) = SharedFuncs.getTHPandOSInitFile()
        cmd = "%s %s mtu 1500;" % (g_Platform.getIfconfigCmd(), networkCardNum)
        cmd += "echo %s %s mtu 1500 >> %s" % (g_Platform.getIfconfigCmd(), networkCardNum, initFile)
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0):
            resultStr += "Set MTU Filed.Error : %s." % output
        if (len(resultStr) > 0):
            self.result.val = resultStr
        else:
            self.result.val = "Set MTU successfully."
