#!/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.gsplatform import g_Platform
except ImportError as ie:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(ie))


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

    def doCheck(self):
        self.ipAddr, self.service_network_adapt, self.service_network_adapts = \
            SharedFuncs.getLocalIP(self.nodes, self.all_network_info)
        networkCardNums = self.service_network_adapts
        flag = True
        for networkCardNum in networkCardNums:
            cmd = "%s -i %s" % (g_Platform.getEthtoolCmd(), networkCardNum)
            output = SharedFuncs.runShellCmd(cmd)
            self.result.raw = "%s[%s]\n%s\n" % (self.result.raw, networkCardNum, output)
            NICVer = ""
            PCIAddr = ""
            for eachLine in output.split("\n"):
                if eachLine.startswith("version:"):
                    NICVer = eachLine
                if eachLine.startswith('bus-info:'):
                    if len(eachLine.split(':')) == 4:
                        PCIAddr = eachLine.split(':')[2] + ':' + eachLine.split(':')[3]
            if NICVer:
                self.result.val = "%s%s\n" % (self.result.val, NICVer)
            else:
                self.result.val = "%sFailed to get NIC %s 'version' info\n" % (self.result.val, networkCardNum)
                flag = False
            if PCIAddr:
                cmd = "lspci |grep %s" % PCIAddr
                (status, output) = subprocess.getstatusoutput(cmd)
                self.result.raw = "%s%s\n" % (self.result.raw, output)
                if status == 0 and len(output.split(':')) == 3:
                    modelInfo = output.split(':')[2].split('(')[0]
                    self.result.val = "%smodel: %s\n" % (self.result.val, modelInfo.strip())
                else:
                    self.result.val = "%sFailed to get NIC %s model 'bus-info' info\n" % (self.result.val,
                                                                                          networkCardNum)
                    flag = False
            else:
                self.result.val = "%sFailed to get NIC %s model 'bus-info' info\n" % (self.result.val, networkCardNum)
                flag = False

        if flag:
            self.result.rst = ResultStatus.OK
        else:
            self.result.rst = ResultStatus.NG
