#! /usr/bin/env python

# Copyright C 2008-2013 by Isilon Systems LLC. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
# 
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
# 
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems. 
#  
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

import ast
import isi.error
import isi.hw.hal as hal
import isi.hw.vmx as vmx
import isi.gconfig as gcfg
import isi.app.lib.procs as procs

def dump_capabilities():
    ctx = gcfg.open(hal.gcfg_hwinventory).ctx_new()
    hwcap = ctx.read("hwcapabilities")
    max_width = max(map(lambda c: len(str(c)), hwcap))
    for cap, value in hwcap.iteritems():
        print 'Capability: %-*s Value: %s' % (max_width, cap, value)

def convert_capability_value(value):
    result = value
    if isinstance(value, str):
        value = value.lower()
        if value == 'true':
            result = True
        elif value == 'false':
            result = False
        elif value.isdigit():
            result = long(value)
    return result 

def build_capabilities():
    capabilities = {}
    ctx = gcfg.open(hal.gcfg_hwinventory).ctx_new()
    hwcap = ctx.read("hwcapabilities")
    max_width = max(map(lambda c: len(str(c)), hwcap))
    for cap, value in hwcap.iteritems():
        try:
            cap_str = "guestinfo.%s" % cap
            vmx_val = vmx.ConfigGetString(cap_str)
            capabilities[cap] = convert_capability_value(vmx_val)
        except:
            capabilities[cap] = value 
    capabilities['netinfo'] = build_netinfo()
    return capabilities

def build_internal_ifaces():
    internal_ifaces = []
    try:
        ifaces = vmx.ConfigGetString('guestinfo.internal_interfaces')
	ifaces = ast.literal_eval(ifaces)
        order = 0
        for iface in ifaces:
            netinfo = {} 
            iface = iface.strip(' ')
	    iface = hal.getNicNameFromMac(iface) if ":" in iface else iface
            netinfo['name'] = str(iface)
            netinfo['pciinfo'] = ""
            netinfo['group'] = long(1)
            netinfo['type'] = long(hal.getNicTypeFromName(iface))
            netinfo['order'] = order
            internal_ifaces.append(netinfo)
            order = order + 1
    except:
        print 'Unable to read internal interfaces guest info'
    return internal_ifaces

def build_external_ifaces():
    external_ifaces = []
    guestinfo = ['external_gige_interfaces', 'external_10gige_interfaces']
    try:
        for info in guestinfo:
            ifaces = vmx.ConfigGetString('guestinfo.%s' % info)
	    ifaces = ast.literal_eval(ifaces)
            order = 0
            for iface in ifaces:
                if len(iface) == 0:
                    continue 	
                netinfo = {}
                iface = iface.strip(' ')
		iface = hal.getNicNameFromMac(iface) if ":" in iface else iface
                netinfo['name'] = str(iface)
                netinfo['pciinfo'] = ""
                netinfo['group'] = long(0)
                netinfo['type'] = long(hal.getNicTypeFromName(iface))
                netinfo['order'] = order
                external_ifaces.append(netinfo)
                order = order + 1
    except:
        print 'Unable to read external interfaces guest info'
    return external_ifaces 

def build_netinfo():
    internal_ifaces = build_internal_ifaces()
    external_ifaces = build_external_ifaces()
    return internal_ifaces + external_ifaces

def revert_capabilities():
    status = 0
    ctx = gcfg.open(hal.gcfg_hwinventory).ctx_new()
    ctx.revert_to_default('hwcapabilities')
    try:
        ctx.commit()
    except isi.error.IsiSystemError, e:
        print ('Exception ("%s") while reverting hardware capabilities '
               'to defaults' % str(e))
        status = 1
    return status

def write_capabilities(capabilities):
    status = 0
    capabilities['initted'] = True
    ctx = gcfg.open(hal.gcfg_hwinventory).ctx_new()
    try:
        ctx.write('hwcapabilities', capabilities)
        ctx.commit()
    except isi.error.IsiSystemError, e:
        print ('Exception ("%s") while writing and/or committing '
               'hardware capability cache' % str(e))
        status = 1
    return status

def generate_capabilities():
    status = revert_capabilities() 
    if status:
        print 'Unable to revert HW Capabilities, aborting.'
    capabilities = build_capabilities()
    if write_capabilities(capabilities):
        print 'Unable to write HW Capabilities, aborting.'

if __name__ == "__main__":
    generate_capabilities()
