#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    import os
    import subprocess
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.common.Common import DefaultValue
    from gspylib.os.gsfile import g_file
    from gspylib.os.gsnetwork import g_network
    from gspylib.os.platform import support_platform
    from gspylib.os.gsplatform import g_Platform
except ImportError as e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


class CheckBond(BaseItem):
    def __init__(self):
        super(CheckBond, self).__init__(self.__class__.__name__)

    def doCheck(self):
        networkCardNum = self.service_network_adapt.NICNum
        networkConfigFile = SharedFuncs.getNetWorkConfFile(networkCardNum)
        netBondMode = g_Platform.getNetworkBondModeInfo(networkConfigFile, networkCardNum)
        self.result.val = netBondMode
        self.result.rst = ResultStatus.OK
        self.result.raw = "%s\n%s\n" % (networkCardNum, netBondMode)
        bondFile = DefaultValue.getNetWorkConfFile(networkCardNum)
        if (os.path.exists(bondFile)):
            self.result.raw += bondFile
            flag1 = g_file.readFile(bondFile, 'BONDING_OPTS')
            flag2 = g_file.readFile(bondFile, 'BONDING_MODULE_OPTS')
            if (not flag1 and not flag2):
                self.result.rst = ResultStatus.NG
                self.result.val += "\nNo 'BONDING_OPTS' or 'BONDING_MODULE_OPTS' in bond config file[%s]." % bondFile

    def doSet(self):
        ifcfgFileSuse = "/etc/sysconfig/network/ifcfg-%s" % self.service_network_adapt.NICNum
        ifcfgFileRedhat = "/etc/sysconfig/network-scripts/ifcfg-%s" % self.service_network_adapt.NICNum
        gs_platform = g_Platform()
        distname, _, _ = gs_platform.dist()
        if distname.lower() == support_platform.SUSE:
            cmd = "echo BONDING_MODULE_OPTS='mode=%d miimon=100 use_carrier=0' >> %s " % (1, ifcfgFileSuse)
        else:
            cmd = "echo BONDING_MODULE_OPTS='mode=%d miimon=100 use_carrier=0' >> %s " % (1, ifcfgFileRedhat)
        (status, _) = subprocess.getstatusoutput(cmd)
        if (status != 0):
            self.result.val = "Filed to set bond mode.\n"
        else:
            self.result.val = "set bond mode successfully.\n"
