#!/usr/bin/python

# This script was added as a result of Service Enhancement Request (SER) #1516
# It takes select CTO information from the asbuilt record and summarizes it into
# a concise, easy to read format for use by those who service Isilon products.

import os
import sys
import isi.hw.hal as hal
import isi.app.lib.procs as procs
import xml.etree.ElementTree as ET

def main():
    if not hal.supportsCto():
        print '%s: Tool is only supported on CTO capable nodes' % sys.argv[0]
        sys.exit(1)

    cmd = 'isi_inventory_tool --display --itemType asbuilt'
    (error, asbuilt) = procs.get_cmd_output(cmd)
    if error:
        print '%s: Tool failed to gather CTO information' % sys.argv[0]
        sys.exit(1)

    try:
        root = ET.fromstring('\n'.join(asbuilt))
    except:
        print '%s: Tool failed to parse gathered CTO information' % sys.argv[0]
        sys.exit(1)

    print 'S/N:', hal.getChassisSerialNumber(0)
    print 'P/N:', hal.getChassisConfigNumber(0)
    for section in root:
        if section.tag == 'bom':
            print '\nBill of Materials:'
            for sbb in section:
                part = sbb.get('part')
                desc = sbb.get('desc')
                print part, desc
                for item in sbb:
                    for subitem in item:
                        qty = subitem.get('qty')
                        part = subitem.get('part')
                        desc = subitem.get('desc')
                        print '    %2s x %s %s' % (qty, part, desc)
        elif (section.tag == 'missing'
                and section.get('containsMissing') == 'True'):
            print '\nMissing:'
            for item in section:
                qty = item.get('qty')
                part = item.get('part')
                desc = item.get('desc')
                print '    %2s x %s %s' % (qty, part, desc)
        elif (section.tag == 'unexpected'
                and section.get('containsUnexpected') == 'True'):
            print '\nUnexpected:'
            for item in section:
                qty = item.get('qty')
                part = item.get('part')
                desc = item.get('desc')
                print '    %2s x %s %s' % (qty, part, desc)

if __name__ == '__main__':
    main()
