#!/usr/bin/python

"""
    This module contains the deployment script to create a RAID volume using CmdTool2
"""

import string, os, os.path, shutil, sys, popen2, systemMgr
from logMgr import addLogRecord,CRITICAL,ERROR,WARNING,INFO,DEBUG
from config import DeploymentStore, DeployPath
from config import getstatusoutput
from deploymentData import ATSTATE,FAILURE,UPDATE,REFRESH,REBOOT,UNSUPPORTED
try:
    __file__
except:
    __file__ = __name__

def checkBIOS(HW,restore=0):
    """
        checkBIOS() returns ATSTATE if at desired state
        checkBIOS() returns FAILURE if state can't be achieved
        checkBIOS() returns UPDATE if system info refresh is needed once configured
    """
    ret, value = systemMgr.queryProperty(0,'IntelBIOSID','BoardFamilyID','S5000',{})
    if not ret == 1:
        print 'CmdTool2 is supported on S5000 systems only'
        #addLogRecord(0,__file__, INFO,'CmdTool2 is supported on S5000 systems only')
        return -1
    ret, value = systemMgr.queryProperty(0,'BIOSRAID','HWRAID','Enabled',{})
    if not HW and ret == 1:
        print 'HWRAID is installed, skipping SWRAID configuration'
        addLogRecord(0,__file__, INFO,'HWRAID is installed, skipping SWRAID configuration')
        return -1
    if HW and not ret == 1:
        print 'HWRAID is not installed'
        addLogRecord(0,__file__, INFO,'HWRAID is not installed')
        return -1
    if not HW:
        ret, value = systemMgr.queryProperty(0,'BIOSRAID','SWRAID','Enabled',{})
        if not ret == 1:
            #print 'BIOS setting for SWRAID is not enabled'
            #addLogRecord(0,__file__, INFO,'BIOS setting for SWRAID is not enabled')
            return UPDATE
    return ATSTATE


def CreateVolume(HW,restore=0):
    state = checkBIOS(HW,restore)
    if state < 0:
        return ATSTATE
    if state == UPDATE:
        ret, chassis = systemMgr.queryProperty(0,'FRU','Chassis OEM Field','',{'info':'Mainboard FRU'})
        if ret:
            addLogRecord(0,__file__, ERROR,'chassis unavailable: ret = %d'%ret)
            return FAILURE
        from detectBIOSRAID import setSWRAID
        if chassis == 'NSW1U':
            setSWRAID(1,1,0) # enable, SATA, LSI
        else:
            setSWRAID(1,0,0) # enable, SAS, LSI
        return REBOOT

    if restore:
        count = 0
        HW, value = systemMgr.queryProperty(0,'BIOSRAID','HWRAID','Enabled'):
        SW, value = systemMgr.queryProperty(0,'BIOSRAID','SWRAID','Enabled'):
        if HW:
            count = systemMgr.countProperty(0,'Disk','device',{"type":"HWRAID"})
        elif SW:
            count = systemMgr.countProperty(0,'Disk','device',{"type":"SWRAID"})
        else:
            return ATSTATE
        if count == 0:
            return ATSTATE
        args = '-CfgLDDel -L0 -a0' #clears Logical Drive 0 on Adapter 0 
        status, output = getstatusoutput("CmdTool2 %s"%args)
        #No error handling hear just in case there are no volumes to clear.
        #Clear previous RAID volumes and configuration information:
        args = '-CfgClear -aALL'
        status, output = getstatusoutput("CmdTool2 %s"%args)
        print "RAID logical volume 0 deleted using CmdTool2"
        addLogRecord(0,__file__, INFO,"RAID logical volume 0 deleted using CmdTool2")
        return REFRESH

    print "running an example of configuring a RAID using CmdTool2 ..."

    #Inquire if the RAID driver is running
    args = '-LDInfo -L0 -a0'
    status, output = getstatusoutput("CmdTool2 %s"%args)
    if status:
        print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
        addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
        return FAILURE
    for line in output:
        if not line.find("No Virtual drive configured") < 0:
            break
    else:
        print "RAID exists on Adapter 0"
        addLogRecord(0,__file__, INFO,"RAID exists on Adapter 0:\n%s"%output)
        return state

    # find 2 disks:
    DiskA=''
    DiskB=''
     
    for N in [0, 1, 2, 3, 4, 5, 6]:
        ret, device = systemMgr.queryProperty(0,'Disk','device','',{"slot":"%d"%N})
        if not ret:
            if not DiskA:
                DiskA='%d'%N
            else:
                DiskB='%d'%N
                break
    else:
        print "need at least 2 disk for RAID"
        addLogRecord(0,__file__, ERROR,"need at least 2 disk for RAID")
        return FAILURE

    #Get Enclosure Device ID
    HW, value = systemMgr.queryProperty(0,'BIOSRAID','HWRAID','Enabled')
    if HW:
        args = '-EncInfo -a0'
        status, output = getstatusoutput("CmdTool2 %s"%args)
        if status:
            print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
            addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
            return FAILURE
        for line in output:
            if line.find('Device ID') >= 0:
                EID = line.split(':')[1].strip()
                break
        else:
            print "Failed to locate the HW RAID enclosure device id in %s"%(output)
            addLogRecord(0,__file__, ERROR,"Failed to locate the HW RAID enclosure device id in %s"%(output))
            return FAILURE
    else:
        EID=''

    #Create RAID 0 Volume using the first 2 disks:
    args = '-CfgLDAdd -R0[%s:%s,%s:%s] -a0'%(EID,DiskA,EID,DiskB)
    status, output = getstatusoutput("CmdTool2 %s"%args)
    if status:
        print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
        addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
        return FAILURE

    #Initialize the New Volume
    args = '-LDInit -Start Full -L0 -a0'
    status, output = getstatusoutput("CmdTool2 %s"%args)
    if status:
        print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
        addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
        return FAILURE

    #Display the initialization progress
    args = '-LDInit -ProgDsply -L0 -a0'
    status, output = getstatusoutput("CmdTool2 %s"%args)
    if status:
        print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
        addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
        return FAILURE

    print "RAID created using CmdTool2"
    addLogRecord(0,__file__, INFO,"RAID created using CmdTool2")

    #Set Disk Cache
    args = '-LDSetProp WB -L0 -a0'
    status, output = getstatusoutput("CmdTool2 %s"%args)
    if status:
        print "'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output)
        addLogRecord(0,__file__, ERROR,"'CmdTool2 %s' failed: status = 0x%x, %s"%(args,status,output))
        return FAILURE

    if sys.platform == 'win32':
        return REFRESH
    return REBOOT

if __name__ == '__main__':
    """
    this script assumed these enviroment variables have been set:
    (see deploy.sh or deploy.cmd)
        DeployPath
        DeploymentStore
        PATH
        LD_LIBRARY_PATH (Linux)
        PYTHONPATH
    """
    if len(sys.argv) == 1:
        restore = 0
    elif len(sys.argv) == 2 and sys.argv[1] == '0':
        restore = 0
    else:
        restore = 1
    HW = 0
    if len(sys.argv) == 3:
        if sys.argv[2] == '0':
            HW = 0
        else:
            HW = 1
    state = CreateVolume(restore)
    if state == REBOOT:
        print 'CmdTool2 requires a reboot to effect BIOS RAID configuration changes'
        addLogRecord(0,__file__, INFO,'CmdTool2 requires a reboot to effect BIOS RAID configuration changes')
    elif state == REFRESH:
        os.system('prepareDeployment refresh')
        state = ATSTATE
    if state == ATSTATE:
        print 'CmdTool2 CreateVolume succeeded'
        addLogRecord(0,__file__, INFO,'CmdTool2 CreateVolume succeeded')
    sys.exit(state)
