#!/usr/bin/python

"""
    This module contains the deployment script to run syscfg
"""

import string, os, os.path, shutil, sys, popen2, systemMgr
from logMgr import addLogRecord,CRITICAL,ERROR,WARNING,INFO,DEBUG
from config import DeploymentStore, DeployPath
try:
    __file__
except:
    __file__ = __name__

keywords = {'disk':['Disk','flash','emor'],'cd':['CD-ROM','RMM'],'floppy':['FDD'],'net':[' GE ']}

def runSyscfg(args):
    status = 0
    cwd = os.getcwd()
    cmd = "syscfg %s"%args

    if sys.platform == 'win32':
        filePath = os.path.join(DeployPath,'win32','syscfg')
        os.chdir(filePath)
        r, w, e = popen2.popen3('%s'%cmd,-1,'b')
        elines = e.read()
        e.close()
        lines = r.read()
        r.close()
        w.close()
        if elines:
            print elines
            status = 1
        elif lines.find('FAILURE') >= 0 or lines.find('failed') >= 0:
            status = 1
    
    elif sys.platform == 'linux2':
        filePath = os.path.join(DeployPath,'Linux','syscfg')
        os.chdir(filePath)
        cmdObj = popen2.Popen4('./%s'%cmd)
        status = cmdObj.wait()
        lines = cmdObj.fromchild.read()

    if status:
        addLogRecord(0,__file__, ERROR,'%s command failed: status = 0x%x, %s'%(cmd,status,lines))
    os.chdir(cwd)
    """
    lines = [
    '',
    'Boot Device Priority',
    '1:  Primary Slave CD-ROM',
    '2:          USB Flash Memory1.00',
    '3:  USB 2.0 SysCon Settings Management',
    '4:  IBA GE Slot 0701 v1245',
    '5:  USB 1.1 SysCon Settings Management',
    '6:  [EFI Shell]',
    ]
    """

    return status, lines.split('\n')

def getBootOrder(restore=0):
    args = '/bbo'
    status, lines = runSyscfg(args)
    if status:
        return {}
    bootdict = {}
    for line in lines:
        #print line
        parts = line.split(':')
        if not len(parts) == 2:
            continue
        bootdict[parts[0].strip()] = parts[1].strip()
    return bootdict

def biosConfig(order,restore=0):
    
    print "running an example of configuring the boot order using syscfg ..."
    
    bootdict = getBootOrder()
    #print order
    #print bootdict
    neworder = []
    unref = []
    for word in order:
        for index in bootdict.keys():
            for clue in keywords[word]:
                if clue in bootdict[index]:
                    if 'SysCon Settings Management' in bootdict[index]:
                        continue
                    if index in unref:
                        del unref[unref.index(index)]
                    if not index in neworder:
                        neworder.append(index)
                    break
            else:
                if not index in neworder and not index in unref:
                    unref.append(index)
    unref.sort()
    orderstr = ''
    for index in neworder:
        orderstr = orderstr + ' ' + index
    for index in unref:
        orderstr = orderstr + ' ' + index
    args = '/bbo %s'%orderstr
    print args
    status, lines = runSyscfg(args)
    addLogRecord(0,__file__, INFO,"boot order change attempted with syscfg %s (%s), starting with %s"%(args,order,bootdict))
    return status

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
    and this script has been run:
        prepareDeployment
    """

    usage = """%s [disk cd floppy net]
       This script attempts to change the boot order using syscfg.
       Since it uses string matching to guess what the device type is,
       the string dictionary 'keywords' in this script may need changing to
       properly recognize the devices in a particular system.
       If a device type, e.g. floppy, is not present in the current boot order,
       the option is ignored.
       EFI shell is always left at the end of the boot order
       !! Use at your own risk !!
    """
    order = []
    if len(sys.argv) == 1:
        print usage%sys.argv[0]
        sys.exit(0)
    for word in sys.argv:
        if word == sys.argv[0]:
            continue
        if not keywords.has_key(word):
            print usage%sys.argv[0]
            sys.exit(1)
        order.append(word)
    status = biosConfig(order)
    sys.exit(status)
