#!/usr/bin/python
# -*- coding: latin-1 -*-
# INTEL CONFIDENTIAL
# Copyright 2007 Intel Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents related to the
# source code (Material) are owned by Intel Corporation or its suppliers or
# licensors. Title to the Material remains with Intel Corporation or its
# suppliers and licensors. The Material may contain trade secrets and
# proprietary and confidential information of Intel Corporation and its
# suppliers and licensors, and is protected by worldwide copyright and trade
# secret laws and treaty provisions. No part of the Material may be used,
# copied, reproduced, modified, published, uploaded, posted, transmitted,
# distributed, or disclosed in any way without Intels prior express written
# permission. 
# No license under any patent, copyright, trade secret or other intellectual
# property right is granted to or conferred upon you by disclosure or delivery
# of the Materials, either expressly, by implication, inducement, estoppel or
# otherwise. Any license under such intellectual property rights must be express
# and approved by Intel in writing.
#
# Include any supplier copyright notices as supplier requires Intel to use.
#
# Include supplier trademarks or logos as supplier requires Intel to use, preceded
# by an asterisk. An asterisked footnote can be added as follows:
# *Third Party trademarks are the property of their respective owners.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intels suppliers
# or licensors in any way.

"""This module contains the methods to create and update the deployment log file

"""
__author__ = 'Todd C Davis'
__Product__ = 'Intel_PDK'

import os, os.path, sys, popen2, shutil, warnings, systemMgr
from logMgr import addLogRecord,CRITICAL,ERROR,WARNING,INFO,DEBUG
from config import BMCfamilies, getstatusoutput, DeployPath
from driverMap import OSdrivers

try:
    __file__
except:
    __file__ = __name__

if sys.platform == 'linux2':
    import glob
    global drvPath
    def getdrvPath():
        return os.path.join(DeployPath,'Linux','drivers')
        """
        status, lines = getstatusoutput('uname -r')
        if status:
            print "Failed to find kernel release, status = 0x%x"%status
            addLogRecord(0,__name__, ERROR,"Failed to find kernel release, status = 0x%x"%status)
            return ''
        for line in lines:
            if not line:
                continue
            for ver in OSversions.keys():
                if line.find(OSversions[ver]) >= 0:
                    return os.path.join(DeployPath,'Linux','drivers',ver)
            else:
                print "Unsupported kernel release %s"%line
                addLogRecord(0,__name__, ERROR,"Unsupported kernel release %s"%line)
        return ''
        """
    def rh3update():
        syscfgtar = 'syscfg-el3.tar.gz'
        cwd = os.getcwd()
        os.chdir(os.path.join(DeployPath,'Linux','syscfg'))
        if os.path.exists('ENUS'):
            os.system('rm -rf ENUS')
        os.system('tar -xzf %s'%syscfgtar)
        os.chdir('lib')
        import glob
        for f in glob.glob('*.1.0'):
            shutil.copy2(f,os.path.join('..','..','libs',f[:-4]))
        os.chdir('..')
        os.system('rm -rf lib')
        os.system('rm -rf drivers')
        os.chdir(cwd)

    def extractDrivers():
        status, lines = getstatusoutput('uname -r')
        if status:
            print "Failed to find kernel release, status = 0x%x"%status
            addLogRecord(0,__name__, ERROR,"Failed to find kernel release, status = 0x%x"%status)
            sys.exit(1)
        for line in lines:
            if not line:
                continue
            for ver in OSdrivers.keys():
                if line.find(OSdrivers[ver][0]) >= 0:
                    addLogRecord(0,__name__, INFO,"Linux version: %s"%line)
                    pkg = OSdrivers[ver][1]
                    if ver == 'rh3':
                        rh3update()
                    break
            else:
                print "Unsupported kernel release %s"%line
                addLogRecord(0,__name__, ERROR,"Unsupported kernel release %s"%line)
                sys.exit(1)
        dstdir = getdrvPath()
        cwd = os.getcwd()
        os.chdir(dstdir)
        for f in glob.glob('*.ko'):
            os.remove(f)
        os.system('tar -xzf %s'%pkg)
        os.system('chmod +x *.ko')
        os.system('chmod +x *.o')
        for f in glob.glob('*.sh'):
            os.remove(f)
        #cp -f amifldrv_mod.o-dmiedit $pdk_dir/Linux/drivers/s5000/amifldrv_mod.o
        for arch in ['S3000','S5000','S5500']:
            if not os.path.exists(arch):
                os.mkdir(arch)
            shutil.copy2('amifldrv_mod.o-dmiedit',os.path.join(arch,'amifldrv_mod.o'))
            #shutil.copy2('amifldrv_mod.o-dmiedit',os.path.join('S5000','amifldrv_mod.o'))
        os.remove('amifldrv_mod.o-dmiedit')
        #need smidrv and imbdrv scripts from slax archive
        #RH3 does not have Python tarfile
        if not os.path.exists('imbdrv'):
            os.system('tar -xzf %s ./imbdrv'%OSdrivers['slax'][1])
        os.system('chmod +x ./imbdrv')
        if not os.path.exists('smidrv'):
            os.system('tar -xzf %s ./smidrv'%OSdrivers['slax'][1])
        os.system('chmod +x ./smidrv')
        # need some startup scripts from SLAX
        #if not drv == 'slax':
        #    for f in ['imbdrv','smidrv']:
        #        shutil.copy2(os.path.join('..','slax',f),f)
        os.chdir(cwd)

    def isLoaded(driver):
        cmdObj = popen2.Popen4('lsmod')
        status = cmdObj.wait()
        lines = cmdObj.fromchild.read()
        if lines.find(driver) < 0:
            return 0
        return 1

    def startSpyService():
        os.system("%s"%os.path.join(DeployPath,'Linux','spy','Spy'))

if sys.platform == 'win32':
    def lsPCI():
        # Routine to grab all the enumerated PCI devices from the registry.  If successful, returns dictionary
        # of device descriptions indexed on HwID for each; otherwise, returns an empty dictionary.
        import _winreg
        PCIdict = {}
     
        # First open the registry hive
        try:
            Hive = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
        except WindowsError:
            print "Can't connect to registry hive HKEY_LOCAL_MACHINE."
            return PCIdict
     
        # Then open the registry key where Windows stores the Shell Folder locations
        try:
            Key = _winreg.OpenKey(Hive, "SYSTEM\CurrentControlSet\Enum\PCI")
        except WindowsError:
            print "Can't open registry key SYSTEM\CurrentControlSet\Enum\PCI."
            _winreg.CloseKey(Hive)
            return PCIdict
     
        # Nothing failed above, so enumerate through all the PCI values and return in a dictionary
        # This relies on error at end of 
        try:
            #i = 0
            #while 1:
            for i in range(0, _winreg.QueryInfoKey(Key)[0]):  # query subkeys
                PCIkey = _winreg.EnumKey(Key, i)
                #print PCIkey
                subkey = _winreg.OpenKey(Key,PCIkey)
                for n in range(0, _winreg.QueryInfoKey(subkey)[0]): # query subkeys
                    subkeyName = _winreg.EnumKey(subkey, n)
                    #print subkeyName
                    dataKey = _winreg.OpenKey(subkey,subkeyName)
                    for d in range(0, _winreg.QueryInfoKey(dataKey)[1]): # query data
                        valueName, value, val_type = _winreg.EnumValue(dataKey, d)
                        #print valueName
                        if valueName == 'DeviceDesc':
                            PCIdict['PCI\\'+PCIkey] = value
                    _winreg.CloseKey(dataKey)
                _winreg.CloseKey(subkey)
            _winreg.CloseKey(Key)                           # Only use with for loop
            _winreg.CloseKey(Hive)                          # Only use with for loop
            return PCIdict                                  # Only use with for loop
        except WindowsError:
            # In case of failure before read completed, don't return partial results
            print "Windows Error"
            _winreg.CloseKey(Key)
            _winreg.CloseKey(Hive)
            return {}
            

    HWRAIDvendors = { #LSI HW RAID
        'TIGW1U'  : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'SR2500LX': ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'NSC2U'   : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'NSN2U'   : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'TIGH2U'  : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
    }
    SWRAIDvendors = { #LSI SW RAID
        'TIGW1U'    : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'SR2500LX'  : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSC2U'     : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSN2U'     : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'TIGH2U'    : ['PCI\VEN_1000',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
    }
    ESB2RAIDvendors = { #ESB2 ATA RAID devices
        'TIGW1U'    : ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSC2U'     : ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSN2U'     : ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSW1U'     : ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'S3000LSI'  : ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','megaide','MegaIDE.INF')],
        'S3000Intel': ['PCI\VEN_8086',os.path.join(DeployPath,'win32','drivers','iastor','iastor.inf')],
    }
    def loadRaidDriver(PCIdict, vendorDict,chassisKey):
        if not vendorDict.has_key(chassisKey):
            return 0
        winInstall = os.path.join(DeployPath,'win32','frusdr','win2kinstall.exe')
        vendor = vendorDict[chassisKey][0]
        raiddrv = vendorDict[chassisKey][1]
        if os.path.exists(raiddrv):
            for key in PCIdict.keys():
                #print PCIdict[key]
                if PCIdict[key] == 'RAID Controller' and key[:12] == vendor:
                    #print key
                    HwIdKey = key
                    break
                elif PCIdict[key] == 'SCSI Controller' and key[:12] == vendor:
                    #print key
                    HwIdKey = key
                    break
            else:
                #addLogRecord(0,__name__, WARNING,'RAID vendor "%s" not found for %s'%(vendor,chassisKey))
                return 0
            # win2kInstall always returns an error status
            ret = os.system('%s %s "%s"'%(winInstall,raiddrv,HwIdKey))
            #if ret:
            #    addLogRecord(0,__name__, WARNING,'%s failed to load: status = 0x%x'%(raiddrv,ret))
            #else:
            return 1
        else:
            addLogRecord(0,__name__, WARNING,'%s driver not found'%(raiddrv))
        return 0

    """
    HWRAIDHwIds = { #LSI HW RAID
        'TIGW1U'  : ['PCI\VEN_1000&DEV_0411&SUBSYS_34908086',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'SR2500LX': ['PCI\VEN_1000&DEV_0411&SUBSYS_34908086',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'NSC2U'   : ['PCI\VEN_1000&DEV_0411&SUBSYS_35078086',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
        'TIGH2U'  : ['PCI\VEN_1000&DEV_0411&SUBSYS_35078086',os.path.join(DeployPath,'win32','drivers','IR3','oemsetup.inf')],
    }
    SWRAIDHwIds = { #LSI SW RAID
        'TIGW1U'    : ['PCI\VEN_1000&DEV_0055&SUBSYS_34918086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'SR2500LX'  : ['PCI\VEN_1000&DEV_0055&SUBSYS_35048086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSC2U'     : ['PCI\VEN_1000&DEV_0055&SUBSYS_35078086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'TIGH2U'    : ['PCI\VEN_1000&DEV_0055&SUBSYS_35078086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
    }
    SCSIadapterHwIds = { #SCSI adapter for ATA RAID devices
        'TIGW1U'    : ['PCI\VEN_8086&DEV_2682&SUBSYS_34918086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSC2U'     : ['PCI\VEN_8086&DEV_2682&SUBSYS_346D8086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSW1U'     : ['PCI\VEN_8086&DEV_2682&SUBSYS_34978086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'NSW1UFrontLAN': ['PCI\VEN_8086&DEV_2682&SUBSYS_34958086',os.path.join(DeployPath,'win32','drivers','esrt2','megasr.inf')],
        'S3000LSI'  : ['PCI\VEN_8086&DEV_27C3&SUBSYS_348D8086',os.path.join(DeployPath,'win32','drivers','megaide','MegaIDE.INF')],
        'S3000Intel': ['PCI\VEN_8086&DEV_27C3&SUBSYS_348C8086',os.path.join(DeployPath,'win32','drivers','iastor','iastor.inf')],
    }
    """
    import warnings
    warnings.simplefilter('ignore',FutureWarning)
    def startSpyService():
        srv = 'SpySer'
        r, w, e = popen2.popen3('sc query %s'%srv,-1,'b')
        elines = e.read()
        e.close()
        lines = r.read()
        r.close()
        w.close()
        if elines:
            #print elines
            addLogRecord(0,__file__, ERROR,'sc query %s failed: status = 0x%x, %s'%(srv,e,elines))
            return 1
        if lines.find('running') >= 0:
            return 0
        r, w, e = popen2.popen3('net use',-1,'b')
        elines = e.read()
        e.close()
        lines = r.read()
        r.close()
        w.close()
        if elines:
            #print elines
            addLogRecord(0,__file__, ERROR,'net use failed: status = 0x%x, %s'%(e,elines))
            return 1
        if lines.find(srv) < 0:
            srvbin = os.path.join(DeployPath,'win32','SpySer','SpySer.exe')
            r, w, e = popen2.popen3('sc create %s binPath= %s'%(srv,srvbin),-1,'b')
            elines = e.read()
            e.close()
            lines = r.read()
            r.close()
            w.close()
            if elines:
                #print elines
                addLogRecord(0,__file__, ERROR,'sc create %s %s failed: status = 0x%x, %s'%(srv,srvbin,e,elines))
                return 1
        r, w, e = popen2.popen3('sc start %s'%srv,-1,'b')
        elines = e.read()
        e.close()
        lines = r.read()
        r.close()
        w.close()
        if elines:
            #print elines
            addLogRecord(0,__file__, ERROR,'sc start %s failed: status = 0x%x, %s'%(srv,e,elines))
            return 1
        import time
        time.sleep(6)
        return 0

def loadRAIDDrivers():
    ret, SWRAID = systemMgr.queryProperty(0,'BIOSRAID','SWRAID','',{})
    if ret:
        addLogRecord(0,__name__, ERROR,'BIOSRAID SWRAID unavailable: status = 0x%x'%(ret))
        return ret
    ret, HWRAID = systemMgr.queryProperty(0,'BIOSRAID','HWRAID','',{})
    if ret:
        addLogRecord(0,__name__, ERROR,'BIOSRAID HWRAID unavailable: status = 0x%x'%(ret))
        return ret
    ret, vendor = systemMgr.queryProperty(0,'BIOSRAID','Vendor','',{})
    if ret:
        addLogRecord(0,__name__, ERROR,'BIOSRAID Vendor unavailable: status = 0x%x'%(ret))
        return ret
    ret, family = systemMgr.queryProperty(0,'IntelBIOSID','BoardFamilyID','',{})
    if ret:
        addLogRecord(0,__name__, ERROR,'IntelBIOSID BoardFamilyID unavailable: status = 0x%x'%(ret))
        return ret
    if family in BMCfamilies:
        ret, chassis = systemMgr.queryProperty(0,'FRU','Chassis OEM Field','',{'info':'Mainboard FRU'})
        if ret:
            addLogRecord(0,__file__, ERROR,'chassis unavailable: ret = %d'%ret)
            return ret
    else:   #S3000 family
        chassis = family+vendor
    if sys.platform == 'win32':
        PCIdict = lsPCI()
        if HWRAID == 'Enabled':
            if loadRaidDriver(PCIdict,HWRAIDvendors,chassis):
                PCIdict = lsPCI() # refresh dictionary
            else:
                addLogRecord(0,__name__, WARNING,'HW RAID driver is not loaded for %s'%(chassis))
        if SWRAID == 'Enabled':
            if not loadRaidDriver(PCIdict,SWRAIDvendors,chassis):
                if not loadRaidDriver(PCIdict,ESB2RAIDvendors,chassis):
                    addLogRecord(0,__name__, WARNING,'SW RAID driver not loaded for %s'%(chassis))
                elif chassis == 'S3000LSI':
                    startSpyService()
    if sys.platform == 'linux2':
        cwd = os.getcwd()
        drvPath = getdrvPath()
        if not drvPath:
            sys.exit(1)
        os.chdir(drvPath)
        if family == 'S3000':
            if SWRAID == 'Enabled':
                if vendor == "LSI":
                    raiddrv = os.path.join(drvPath,'megaide.ko')
                    if os.path.exists(raiddrv) and not isLoaded('megaide'):
                        ret = os.system('insmod %s'%raiddrv)
                        if ret:
                            addLogRecord(0,__name__, WARNING,'%s failed to load: status = 0x%x'%(raiddrv,ret))
                        else:
                            startSpyService()
                if vendor == "Intel":
                    addLogRecord(0,__name__, INFO,'Intel RAID supported Windows systems only')
            else:
                addLogRecord(0,__name__, INFO,'RAID not enabled for this %s system'%(family))
        elif family == 'S5000' or family == 'S5500':
            if HWRAID == 'Enabled':
                # The open source HW RAID driver in Slax works
                pass
                #raiddrv = os.path.join(drvPath,'megaraid_sas.ko')
                #if os.path.exists(raiddrv) and not isLoaded('megaraid_sas'):
                #    ret = os.system('insmod %s'%raiddrv)
                #    if ret:
                #        addLogRecord(0,__name__, WARNING,'%s failed to load: status = 0x%x'%(raiddrv,ret))
            elif SWRAID == 'Enabled':
                raiddrv = os.path.join(drvPath,'megasr.ko')
                if os.path.exists(raiddrv) and not isLoaded('megasr'):
                    ret = os.system('insmod %s'%raiddrv)
                    if ret:
                        addLogRecord(0,__name__, WARNING,'%s failed to load: status = 0x%x'%(raiddrv,ret))
            else:
                addLogRecord(0,__name__, INFO,'RAID not enabled for this %s system'%(family))
        else:
            addLogRecord(0,__name__, INFO,'RAID not supported on %s systems'%(family))
        os.chdir(cwd)
    return ret

def loadDiskDrivers():
    """
    LSI reports that there is a conflict between the its Linux megasr/megaide
    SW RAID drivers and the ata_piix driver , a low-level SATA SCSI driver
    for the S3000 and S5000 families.
    To avoid this conflict the ata_piix driver must only be loaded after the 
    SW RAID has been loaded. The ata_piix driver along with other storage drivers will
    not be loaded when the 'nostorage' option is included on the Linux cmdline.
    Since the 'nostorage' option inhibits the loading of many other storage modules
    used to detect and access disks, these modules must be loaded manually after
    loading the megasr driver and the ata_piix driver.
    
    This loadDiskDrivers() function assumes that loadRAIDDrivers() has already
    been called to load the appropriate SW RAID driver. This function will then
    attempt to load the required disk storage drivers.
     
    # cat /proc/cmdline
    initrd=initrd.img ramdisk_size=8192 BOOT_IMAGE=vmlinuz rescue nostorage
    
    On S5000 TIGW1U lsmod:
    Module                  Size  Used by
    ata_piix               15173  0
    libata                111645  1 ata_piix
    mptscsih                1601  0
    mptsas                 21589  4 mptscsih
    mptspi                 10705  1 mptscsih
    mptscsi                43473  2 mptsas,mptspi
    mptbase                66465  3 mptsas,mptspi,mptscsi
    sd_mod                 17345  5
    scsi_mod              125901  5 libata,mptsas,mptspi,mptscsi,sd_mod
    
    If S5000 non-RAID:
    modprobe mptscsih  (should autoload with mptsas)
    modprobe mptbase (should autoload with mptsas)
    modprobe mptscsi  (should autoload with mptsas)
    modprobe mptspi
    modprobe mptsas
    
    modprobe ata_piix  (for cdrom)
    # modprobe libata  (should autoload with ata_piix)
    
    If S5000 SW-RAID:
    modprobe megasr
    modprobe ata_piix  (for cdrom)
    # modprobe libata  (should autoload with ata_piix)
    
    If S3000AH non-RAID:
    if EL3, 
        modprobe ata_piix
    
    if EL4 (verify?):
        modprobe ahci    
    
    If S3000AH SW-RAID:
    modprobe megaide
    """

    if sys.platform == 'linux2':
        ret = 0
        # no force load option for modprobe in Anaconda
        """
        Need to fix this for RAID - Conditional load needed for LSI drivers
        ret, lines = getstatusoutput('insmod ata_piix')
        if ret:
            addLogRecord(0,__name__, INFO,'ata_piix not loaded: status = 0x%x,\n%s'%(ret,lines))

        ret, lines = getstatusoutput('insmod mptspi')
        if ret:
            addLogRecord(0,__name__, INFO,'mptspi not loaded: status = 0x%x,\n%s'%(ret,lines))

        ret, lines = getstatusoutput('insmod mptsas')
        if ret:
            addLogRecord(0,__name__, INFO,'mptsas not loaded: status = 0x%x,\n%s'%(ret,lines))
        """

        cwd = os.getcwd()
        drvPath = getdrvPath()
        if not drvPath:
            sys.exit(1)
        os.chdir(drvPath)
        #lsmod | awk ' { print $1 } ' | grep "^sg$" > /dev/null 2>&1
        #if [ $? != 0 ]
        #then
        #    modprobe sg
        #    sleep 2
        #    sgraidmon -r >/dev/null 2>&1
        #    sleep 1
        #fi
        if not isLoaded('sg'):
            if os.path.exists('sg.ko'):
                ret, lines = getstatusoutput('insmod sg.ko')
                if ret:
                    addLogRecord(0,__name__, WARNING,'insmod sg.ko failed: status = 0x%x,\n%s'%(ret,lines))
            else:
                ret, lines = getstatusoutput('modprobe sg')
                if ret:
                    addLogRecord(0,__name__, WARNING,'modprobe sg failed: status = 0x%x,\n%s'%(ret,lines))
        os.chdir(cwd)
    else:
        ret = 0
    return ret

def loadDrivers():
    if sys.platform == 'win32':
        ret, family = systemMgr.queryProperty(0,'IntelBIOSID','BoardFamilyID','',{})
        winInstall = os.path.join(DeployPath,'win32','drivers','syscfg','DeviceSetup.exe')
        if family and ret == 0:
            #if family == 'S5500':
            #    ret = os.system('%s -v install %s "%s"'%(winInstall,os.path.join(DeployPath,'win32','drivers','syscfg.em64t','IMBDrv.inf'),'*IMBDRV'))
            #    ret = os.system('%s -v install %s "%s"'%(winInstall,os.path.join(DeployPath,'win32','drivers','syscfg.em64t','flashud.inf'),'*INT0800'))
            if family in BMCfamilies:
                #cwd = os.getcwd()
                #drv = os.path.join(DeployPath,'win32','drivers','imbdrv')
                #os.chdir(drv)
                ret, lines = getstatusoutput('%s -v install %s "%s"'%(winInstall,os.path.join(DeployPath,'win32','drivers','syscfg','flashud.inf'),'*INT0800'))
                for line in lines:
                    if line.find('installed successfully') >= 0:
                        addLogRecord(0,__name__, INFO,'DeviceSetup: flashud installed successfully')
                        break
                else:
                    addLogRecord(0,__name__, WARNING,'DeviceSetup: flashud failed to load: status = 0x%x\n%s'%(ret,lines))
                ret, lines = getstatusoutput('%s -v install %s "%s"'%(winInstall,os.path.join(DeployPath,'win32','drivers','frusdr','imbdrv.inf'),'*IMBDRV'))
                for line in lines:
                    if line.find('installed successfully') >= 0:
                        addLogRecord(0,__name__, INFO,'DeviceSetup: imbdrv installed successfully')
                        break
                else:
                    addLogRecord(0,__name__, WARNING,'DeviceSetup: imbdrv failed to load: status = 0x%x\n%s'%(ret,lines))
                ret, lines = getstatusoutput('%s -v install %s "%s"'%(winInstall,os.path.join(DeployPath,'win32','drivers','frusdr','ibsmutil.inf'),'*IntelUtilDeV'))
                for line in lines:
                    if line.find('installed successfully') >= 0:
                        addLogRecord(0,__name__, INFO,'DeviceSetup: ibsmutil installed successfully')
                        break
                else:
                    addLogRecord(0,__name__, WARNING,'DeviceSetup: ibsmutil failed to load: status = 0x%x\n%s'%(ret,lines))
                #if ret:
                #    addLogRecord(0,__name__, WARNING,'%s failed to load: status = 0x%x'%(raiddrv,ret))
                #else:
                #ret = os.system('SetupIMB.exe')
                #if ret:
                #    addLogRecord(0,__name__, WARNING,'imbdrv load failed: status = 0x%x'%(ret))
                #os.chdir(cwd)
            elif family == 'S3000':
                pass
                #cwd = os.getcwd()
                #drv = os.path.join(DeployPath,'win32','drivers','amt')
                #os.chdir(drv)
                #os.chdir(cwd)
        """
        drivers = os.path.join(DeployPath,'win32','drivers')
        drvPath = os.path.join(drivers,'iqvw32.bat')
        ret = os.system('%s'%drvPath)
        if ret:
            addLogRecord(0,__name__, WARNING,'%s failed: status = 0x%x'%(drvPath,ret))
        """
    if sys.platform == 'linux2':
        cwd = os.getcwd()
        drvPath = getdrvPath()
        if not drvPath:
            sys.exit(1)
        os.chdir(drvPath)
        extractDrivers()
        ret = os.system('./smidrv start')
        if ret:
            addLogRecord(0,__name__, WARNING,'smidrv start failed: status = 0x%x'%(ret))
        #drvPath = os.path.join(drvPath,'imb')
        #os.chdir(drvPath)
        ret, family = systemMgr.queryProperty(0,'IntelBIOSID','BoardFamilyID','',{})
        if family and ret == 0:
            dmidir = os.path.join(DeployPath,'Linux','DmiEdit',family)
            dmieditdrv = os.path.join(drvPath,family,'amifldrv_mod.o')
            if os.path.exists(dmieditdrv) and os.path.exists(dmidir):
                shutil.copy2(dmieditdrv,dmidir)
            if family in BMCfamilies:
                if not isLoaded('imb'):
                    ret, lines = getstatusoutput('./imbdrv')
                    if ret:
                        addLogRecord(0,__name__, WARNING,'imbdrv failed: status = 0x%x,\n%s'%(ret,lines))
        drvPath = os.path.join(drvPath,'e1000.ko')
        #os.system('rmmod e1000')
        #ret = os.system('insmod %s'%drvPath)
        #if ret:
        #    addLogRecord(0,__name__, WARNING,'insmod %s failed: status = 0x%x'%(drvPath,ret))
        os.chdir(cwd)
        return ret
    else:
        return 0

if __name__ == '__main__':
    loadDrivers()
    from detectBIOSRAID import detectBIOSRAID
    detectBIOSRAID()
    loadRAIDDrivers()
    loadDiskDrivers()

