#!/usr/bin/env python

# Copyright C 2008-2012 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.

# This script determines if a "isi_fcb_vpd_tool pull" call is necessary
# and calls the pull command if needed.  Also, for Resume EEPROMs,
# this script determines if the Resume EEPROM Isilon VPD (serno AKA
# serial number, and/or partno AKA system config number AKA SysConfig)
# are 'NULL', indicating that the chassis is a FRU replacement chassis
# from a disk tango swap, which is grounds for a "isi_fcb_vpd_tool push"
# of the node's serno/partno data to the Resume.  NOTE that we will use
# use "isi_fcb_vpd_tool write" to update individual Resume values.
# NB: In Freight Trains, disk tangos and 3/4 chassis nodes are DEPRECATED.

import argparse
import os
import sys
import time
import traceback
import random
import re

import logging
import logging.handlers as handlers

from socket import error as socket_error

import isi.hw.bootstrap as bootstrap
import isi.hw.hal as hal
import isi.app.lib.procs as procs

SKU_LEGACY    = 851 # NB: Original isi_vpd_pull code did not have/use 850
SKU_A100      = 105 # NB: Original isi_vpd_pull code did not have/use 105
SKU_CTO_BTS   = 861 # NB: Original isi_vpd_pull code did not have/use 861

SKU_CTO_ISI   = 400 # Original Isilon CTO BOM
SKU_CTO_TLA1  = 900 # Original EMC TLA, incomp w/ Isilon CTO BOM
SKU_CTO_TLA2  = 610 # Replacement EMC TLA for 900, for Isilon CTO BOM

SKU_EMC_TYPE1 = 100
SKU_EMC_TYPE2 = 110 # Infinity (and forward?)

VALID_KNOWN_SKUS = [
    # NB: Excluded from original isi_vpd_pull code: 850 861 105
    # Excluding DEPRECATED 3/4 812 SKU_3QTR
    SKU_LEGACY,
    SKU_CTO_ISI,
    SKU_CTO_TLA1,
    SKU_CTO_TLA2,
    SKU_EMC_TYPE1,
    SKU_EMC_TYPE2,
]

PRE_CTO_SKUS = [
    # Excluding DEPRECATED 3/4 812 SKU_3QTR
    SKU_LEGACY,
    SKU_A100,
    SKU_CTO_BTS, # Remember: BTS is really a SKU NODE!
]

# This is EVERYTHING (previously this excluded 3/4 812 SKU_3QTR, now DEPRECATED)
VALID_PULL_VPD_SKUS = VALID_KNOWN_SKUS

# This is EVERYTHING in PULL_VPD_SKUS EXCEPT LEGACY PRE_CTO_SKUS
VALID_PULL_CTO_PSI_SKUS = set(VALID_PULL_VPD_SKUS).difference(set(PRE_CTO_SKUS))

VALID_RESUME_SKUS = [
    SKU_CTO_TLA1,
    SKU_CTO_TLA2,
    SKU_EMC_TYPE1,
    SKU_EMC_TYPE2,
]

def get_sku(system_config):
    SKU = 0
    if system_config: # handles non-string None case
        for sku in VALID_KNOWN_SKUS:
            if system_config.startswith("%03d-" % sku):
                SKU = sku
                break
    return SKU

SERIAL_FILE = "/etc/isilon_serial_number"
CONFIG_FILE = "/etc/isilon_system_config"

regexVpdSerialNumber = lambda key: re.compile(r"^%s\s*=\s*(?P<val>.*)\s*$" % key)

regexDevidByName = lambda name: re.compile(r'(?P<val>^\d+).*%s.*' % name)

def regex_output_search(regex, output):
    """regex must have a named key 'val' to match against"""
    for line in output:
        result = regex.search(line)
        if result:
            return result.group('val')
    return None

#------------------------------------------------------------------------------

def get_legacy_filename(filename):
    return "$LEGACY_%s" % filename

#------------------------------------------------------------------------------

def supports_resume():
    if hal.supportsResumeEeprom():
        return True
    return False

def supports_eeprom():
    if hal.supportsChassisVpdEeprom():
        return True
    if hal.supportsResumeEeprom():
        return True
    return False

def supports_bmc():
    if hal.supportsBMC():
        return True
    return False

def supports_bmc_vpd():
    if hal.supportsBMCVpd():
        return True
    return False

#------------------------------------------------------------------------------

def print_value(value, name, filename=None, update=False):
    width = len('System Config Number in EEPROM is now') # Worst case
    if value is None:
        log.warning("Could not get %s from %s" %
                      (name, filename and 'disk' or 'EEPROM'))
        return
    if filename:
        desc = '%s contains' % filename
    elif update:
        desc = '%s in EEPROM is now' % name
    else:
        desc = '%s in EEPROM is' % name
    log.info("%-*s: %s" % (width, desc, value))

# There were lots of print(Error: Foo); for line in output: print(Error: line)
# code constructs before. Abstract them all into single common function.
# Retaining the original verbose "Error: %s" labeling for all output.

def print_error(msg, output=[]):
    log.error("Error: %s" % msg)
    for line in output:
        log.error("Error: %s" % line)

#------------------------------------------------------------------------------

def vpd_tool_cmd(cmd, msg=None, ignore_failures=False):
    log.debug("vpd_tool_cmd(cmd=%s, msg=%s)" % (cmd, msg))
    error, output = procs.get_cmd_output(
        '/usr/bin/isi_hwtools/isi_fcb_vpd_tool %s' % cmd)
    if ignore_failures:
        if args.debug:
            log.debug('isi_fcb_vpd_tool %s %s: %s' %
                      (cmd, error and 'failed' or 'success', msg))
            for line in output:
                log.debug('%s' % line)
    else:
        if error and msg:
            print_error('isi_fcb_vpd_tool %s failed: %s' % (cmd, msg), output)
        elif error:
            print_error('isi_fcb_vpd_tool %s failed:' % (cmd), output)
        elif args.debug:
            log.debug('isi_fcb_vpd_tool %s success: output:' % (cmd))
            for line in output:
                log.debug('%s' % line)
    return error, output

#------------------------------------------------------------------------------
# On Infinity hardware - retrieve Chassis/Midplane and Peer-CPU Module
# serial number as part of vpd pull.

_resumes = None # Cached

def eeprom_get_resumes():
    global _resumes
    if not _resumes:
        error, output = vpd_tool_cmd('listresume', "couldn't get available EEPROMs")
        if error:
            return None
        _resumes = output
    return _resumes

def eeprom_get_devid(eeprom_name):
    resumes = eeprom_get_resumes()
    if not resumes:
        return None
    return regex_output_search(regexDevidByName(eeprom_name), resumes)

def eeprom_get_serial_number(eeprom_name, ignore_failures=False):
    """Returns serial number as a string. Returns None on error."""
    # NB: Not all platforms support Resumes, and the listresume command will
    # fail on them: isi_fcb_vpd_tool exposes this command for those platforms
    # only. We could use hal.supportsResumeEeprom as a predicate here, to
    # avoid syslog error spam, but right now this function is ONLY called
    # (via eeprom_pull_additional_info) for the Infinity case.
    log.debug("eeprom_get_serial_number(%s)" % eeprom_name)

    devid = eeprom_get_devid(eeprom_name)
    if devid is None:
        print_error("Unable to determine devid for %s" % eeprom_name)
        return None

    key = 'EMC_TLA_SN'
    error, output = vpd_tool_cmd("-qs --devid=%s read '%s'" % (devid, key),
                                 "couldn't read %s from %s Resume EEPROM" %
                                 (key, eeprom_name),
                                 ignore_failures=ignore_failures)
    if error:
        return None

    serial_number = regex_output_search(regexVpdSerialNumber(key), output)
    if not serial_number and not ignore_failures:
        print_error("Couldn't determine %s from %s Resume EEPROM data" %
                    (key, eeprom_name), output)
    return serial_number

def eeprom_write_serial_number(eeprom_name, serial_number):
    log.debug("eeprom_write_serial_number(%s, %s)" % (eeprom_name, serial_number))

    devid = eeprom_get_devid(eeprom_name)
    if devid is None:
        print_error("Unable to determine devid for %s" % eeprom_name)
        return None

    key = 'EMC_TLA_SN'
    error, output = vpd_tool_cmd("-q --devid=%s write %s '%s'" %
                                 (devid, key, serial_number),
                                 "couldn't write %s to %s Resume EEPROM" %
                                 (key, eeprom_name))
    if error:
        return None
    return serial_number

def eeprom_get_serial_number_from_node(key):
    """Just use vpd tool - no devid - for "mapped" keys, not EEPROM keys"""
    error, output = vpd_tool_cmd("-qs read '%s'" % (key), ignore_failures=True)
    if error:
        return None
    return regex_output_search(regexVpdSerialNumber(key), output)

def _eeprom_pull_additional_info():

    # pull Chassis/Midplane serial number
    name, key = 'Chassis/Midplane', 'CHASSIS_TLA_SN'
    serial_number = eeprom_get_serial_number(name)

    if serial_number is None:
        # Error, unable to read
        pass
    elif serial_number == '':
        # Successfully read, but empty: Chassis Tango situation
        # For log purposes, attempt a VPD read of the key, if it exists on the node,
        # since this is the value that needs to be pushed to the new Chassis.
        node_chassis_serno = eeprom_get_serial_number_from_node(key)
        if node_chassis_serno:
            log.warning("%s has empty (NULL) EMC_TLA_SN value; "
                        "Assuming a Chassis Tango is in progress, "
                        "attempting automatic update using node %s value '%s'." %
                        (name, key, node_chassis_serno))
            eeprom_chassis_tango_push(True, node_chassis_serno)
        else:
            log.warning("%s has empty (NULL) EMC_TLA_SN value; "
                        "If a Chassis Tango is in progress, unable to "
                        "automatically update without node %s value. "
                        "Update using isi_vpd_pull --chassisTango." %
                        (name, key))
    else:
        log.info("%s SN %s: Saving to %s..." % (name, serial_number, key))
        error, output = vpd_tool_cmd("write %s '%s'" % (key, serial_number),
                                     "could not store %s" % key)

    # pull Peer CPU Module serial number
    name, key = 'Peer CPU Module', 'PEER_TLA_SN'
    serial_number = eeprom_get_serial_number(name)

    if serial_number:
        log.info("%s SN %s: Saving to %s..." % (name, serial_number, key))
        error, output = vpd_tool_cmd("write %s '%s'" % (key, serial_number),
                                     "could not store %s" % key)

    # sync vpd info
    error, output = vpd_tool_cmd('sync')

def eeprom_chassis_tango_user_input(name, node_chassis_serno):
    prompt = ("Enter new %s Serial Number [%s]: " %
              (name, node_chassis_serno
               and 'return for previous %s' % node_chassis_serno
               or 'no previous node value'))
    while True:
        new_serno = raw_input(prompt)
        if new_serno == '' and node_chassis_serno: # Return, use default
            new_serno = node_chassis_serno
            break
        # Otherwise pretty loose with validity checking; non-empty,
        # and doesn't exceed Resume EEPROM field size of 0x10.
        # Let's assume it has to have "at least" 12 chars,
        # arbitrary, actual serial numbers seen have been 14.
        # If we felt confident enough, we could regex check this.
        new_serno = new_serno.strip()
        if len(new_serno) >= 12 and len(new_serno) <= 0x10:
            break
    prompt = ("New %s Serial Number = %s: Are you sure? (y/n) [y]:" %
              (name, new_serno))
    while True:
        confirm = raw_input(prompt).strip().lower()
        if confirm in ('', 'y', 'yes'):
            return new_serno
        if confirm in ('n', 'no'):
            return None

def eeprom_chassis_tango_push(automatic=False, node_chassis_serno=None):
    # 1. Chassis/Midplane EMC_TLA_SN must be NULL (empty).
    # 2. If node (disk) CHASSIS_TLA_SN is available, pre-populate the
    #    user choice with this value in the prompt.
    # 3. Else if CHASSIS_TLA_SN is NOT available, prompt will state this.
    # 4. Prompt user for confirmation/input, UNLESS overridden by caller.
    # 5. Perform minimal sanity validation of value.
    # 6. (In attempt to avoid potential situation of multiple nodes
    #    booting simultaneously and automatically doing a tango_push
    #    write to Resume simultaneously): If automatic: Random Delay
    # 7. Attempt write
    # 8. Read back and confirm, reporting success or failure
    desc = 'Chassis Tango Push'
    name, key = 'Chassis/Midplane', 'CHASSIS_TLA_SN'
    # If called automatically, we already did a read and determined NULL;
    # We will do a second read to verify it's still NULL down below.
    # For non-automatic (command line) case, likewise, check NULL below.
    if node_chassis_serno is None:
        node_chassis_serno = eeprom_get_serial_number_from_node(key)
    if automatic:
        if not node_chassis_serno:
            # Can't do automatic (non-interactive) without a node value
            log.error("No %s serial number (%s) available on node; "
                      "Aborting %s" % (name, key, desc))
            return 1
        new_serial_number = node_chassis_serno
    else:
        print("Use the original %s dogtag serial number in prompt below:" % name)
        new_serial_number = eeprom_chassis_tango_user_input(name, node_chassis_serno)
        if not new_serial_number:
            log.error("No valid %s serial number provided; "
                      "Aborting %s" % (name, desc))
            return 1
    if automatic:
        # Sleep for a random amount of time, 'just in case', to avoid
        # multiple nodes booting and hitting this point simultaneously (!)
        random.seed(time.time())
        delay = random.randint(0, 4)
        if delay:
            log.debug("Random sleep(%s) seconds..." % delay)
            time.sleep(delay)
        # After sleep, double-check it's still NULL
    # For both automatic (post-sleep) and command line case: check first
    serial_number = eeprom_get_serial_number(name, ignore_failures=True)
    if serial_number is None:
        # Error, unable to read
        log.error("Unable to read %s serial number; "
                  "Aborting %s" % (name, desc))
        return 1
    if serial_number:
        log.warning("%s already has non-empty serial number '%s'; "
                    "Aborting %s" % (name, serial_number, desc))
        return 1
    result = eeprom_write_serial_number(name, new_serial_number)
    if result is None:
        log.error("Failed to write %s serial number '%s'" %
                  (name, new_serial_number))
        return 1
    log.info("Successfully wrote %s serial number '%s'" %
             (name, new_serial_number))
    return 0

#------------------------------------------------------------------------------

def bmc_pull():
    log.debug('bmc_pull()')
    import isi.hw.dongle as hwdongle
    if hwdongle.bmc_pull():
        log.error("BMC Pull Failed")

def vmx_pull():
    log.debug('vmx_pull()')
    import isi.hw.dongle as hwdongle
    dongle_info_keylist = [
        ('serialno' , '/etc/isilon_serial_number'),
        ('sysconfig', '/etc/isilon_system_config'),
    ]
    if hwdongle.vmx_pull(dongle_info_keylist):
        log.error("VMX Pull Failed")

def eeprom_pull():
    log.debug('eeprom_pull()')
    eepromSerialNumber = diskSerialNumber = None
    eepromSystemConfig = diskSystemConfig = None

    # Get system config from /etc
    try:
        with open(CONFIG_FILE, 'r') as f:
            diskSystemConfig = f.readline().rstrip('\n')
    except EnvironmentError as e:
        diskSystemConfig = None
        log.error("Could not get VPD from disk: %s" % e)
    try:
        with open(SERIAL_FILE, 'r') as f:
            diskSerialNumber = f.readline().rstrip('\n')
    except EnvironmentError as e:
        diskSerialNumber = None
        log.error("Could not get VPD from disk: %s" % e)

    # Determine EEPROM system config and serial number
    regexSystemConfig = re.compile(".*%s\s*:\s*\[?\s*([^]]*)\s*\]?.*" % CONFIG_FILE)
    regexSerialNumber = re.compile(".*%s\s*:\s*\[?\s*([^]]*)\s*\]?.*" % SERIAL_FILE)

    # Get system config from EEPROM
    # Remember any errorDump failure reading from EEPROM - if unable to read,
    # do not write below (updating Resume for NULL SKU or serial number).
    errorDump, output = vpd_tool_cmd('dump', "could not get VPD from EEPROM")

    for line in output:
        match = regexSerialNumber.match(line)
        if match:
            eepromSerialNumber = match.group(1).split(',')[0].strip(" '")
        match = regexSystemConfig.match(line)
        if match:
            eepromSystemConfig = match.group(1).split(',')[0].strip(" '")

    print_value(eepromSystemConfig, 'System Config Number')
    print_value(diskSystemConfig, 'System Config Number', filename=CONFIG_FILE)
    print_value(eepromSerialNumber, 'Serial Number')
    print_value(diskSerialNumber, 'Serial Number', filename=SERIAL_FILE)

    diskSKU = get_sku(diskSystemConfig)
    eepromSKU = get_sku(eepromSystemConfig)

    # Logic for executing VPD write to Resume EEPROM if necessary
    # If either eepromSKU or eepromSerialNumber are NULL, where we
    # define NULL to be an empty string '' (at least first byte in
    # Resume data field is 0x00=='\0'), and we have a valid node
    # SKU/SERNO, attempt write to Resume EEPROM before pull.
    # Never write an 812 SKU_3QTR to EEPROM.  In fact -- ONLY write
    # expected Resume SKU part numbers. (NB: 812 SKU_3QTR has been
    # DEPRECATED in Freight Trains, which minimally affects this code,
    # since VALID_RESUME_SKUS has been update to reflect this.)
    # Never write if previous failure reading EEPROM above, in dump.

    if supports_resume() and (not eepromSKU or not eepromSerialNumber):
        eepromWriteData = {}
        if not eepromSKU and diskSKU in VALID_RESUME_SKUS:
            eepromWriteData[CONFIG_FILE] = diskSystemConfig
        if not eepromSerialNumber and diskSerialNumber:
            # Strip dashes, just in case of legacy style SERNO.
            # Resume EEPROM only accepts 16 char serial numbers.
            eepromWriteData[SERIAL_FILE] = diskSerialNumber.replace('-', '')
        if eepromWriteData and errorDump:
            # Do not write if previous failure reading EEPROM
            print_error("EEPROM may have invalid %s values, "
                        "but isi_fcb_vpd_tool dump failed; "
                        "Not writing VPD to Resume EEPROM from disk" %
                        " and ".join(eepromWriteData.keys()))
        elif eepromWriteData:
            # On success of 'writen' command, this will invalidate our
            # (cached) variables, namely eepromSKU. Update as needed.
            # One approach is to re-do ALL of the above queries specific
            # to the EEPROM. A simpler approach is to merely update our
            # variables before continuing, on successful writes.
            values = ["'%s' '%s'" % (get_legacy_filename(filename), value)
                      for filename, value in eepromWriteData.iteritems()]
            error, output = vpd_tool_cmd(
                'writen %d %s' % (len(eepromWriteData), ' '.join(values)),
                "could not write VPD to Resume EEPROM from disk")
            if not error:
                log.info("Wrote VPD to Resume EEPROM (FRU replacement chassis?):")
                if CONFIG_FILE in eepromWriteData:
                    # Determine updated EEPROM SKU
                    eepromSystemConfig = eepromWriteData[CONFIG_FILE]
                    eepromSKU = get_sku(eepromSystemConfig)
                    print_value(eepromSystemConfig, 'System Config Number',
                                update=True)
                if SERIAL_FILE in eepromWriteData:
                    # Determine updated EEPROM Serial Number (unused...)
                    eepromSerialNumber = eepromWriteData[SERIAL_FILE]
                    print_value(eepromSerialNumber, 'Serial Number',
                                update=True)

    # Logic for executing VPD pull if necessary

    if (eepromSKU in VALID_PULL_VPD_SKUS and diskSKU == 0):
        error, output = vpd_tool_cmd('pull', "could not pull VPD from EEPROM to disk")
        if not error:
            log.info("Pulling VPD from EEPROM to create disk copy")

    elif (eepromSKU in VALID_PULL_VPD_SKUS and diskSKU == eepromSKU):
        error, output = vpd_tool_cmd('pull', "could not pull VPD from EEPROM to disk")
        if error:
            pass # Already reported error; interested in non-error cases below
        elif diskSKU == SKU_LEGACY:
            log.info("Node SKUs appear correct, pulling VPD from EEPROM to disk")
        elif diskSKU in VALID_PULL_CTO_PSI_SKUS:
            log.info("Node System Config Number appears correct, "
                     "pulling VPD from EEPROM to disk")

    else:
        print_error("Not pulling VPD from EEPROM to disk due to invalid "
                    "System Config Number")
        if diskSKU == 0:
            print_error("Invalid System Config Number on disk")
        if eepromSKU == 0:
            print_error("Invalid System Config Number in EEPROM")

def eeprom_sysconfig_read():
    log.debug("eeprom_sysconfig_read()")
    sysconfig = None
    regex = re.compile("\s*\S*%s\s*=\s*\[\s*'(\S+)'\s*.*" % CONFIG_FILE)
    filename = get_legacy_filename(CONFIG_FILE)
    error, output = vpd_tool_cmd("read '%s'" % filename)
    if not error and len(output):
        for line in output:
            match = regex.match(line)
            if match:
                sysconfig = match.group(1)
    return sysconfig

def bmc_sysconfig_read():
    log.debug("bmc_sysconfig_read()")
    sysconfig = None
    cmd = ('/usr/local/sbin/dmidecode -s "chassis-version"')
    error, output = procs.get_cmd_output(cmd)
    if not error and len(output):
        sysconfig = output[0]
    return sysconfig

def reimage_pull():
    log.debug("reimage_pull()")
    if supports_eeprom():
        log.info('Pulling System Config Number from EEPROM')
        sysconfig = eeprom_sysconfig_read()
    elif supports_bmc():
        log.info('Pulling System Config Number from BMC')
        sysconfig = bmc_sysconfig_read()
    else:
        sysconfig = None
    if sysconfig:
        log.info('System Config Number: %s' % sysconfig)
        with open(CONFIG_FILE, 'w') as f:
            f.write('%s\n' % sysconfig)
            f.flush()
        return 0
    else:
        log.error('Unable to get System Config Number')
        return 1

def init_logging(level=logging.INFO):
    my_logger = logging.getLogger('isi_vpd_pull')
    my_logger.setLevel(level)
    try:
        sh = handlers.SysLogHandler(address='/var/run/log',
                                    facility=handlers.SysLogHandler.LOG_DAEMON)
        sf = logging.Formatter('%(name)s: %(message)s')
        sh.setFormatter(sf)
        my_logger.addHandler(sh)
    except socket_error:
        # Too early in boot for syslog
        pass
    ch = logging.StreamHandler()
    my_logger.addHandler(ch)
    return my_logger

parser = argparse.ArgumentParser(
    description=("Perform VPD pulls to node, as necessary. "
                 "Also, for Resume EEPROMs, determines if the Resume EEPROM "
                 "Isilon VPD (serial number, and/or system config number) "
                 "are 'NULL', indicating that either (a) the chassis is a "
                 "FRU replacement chassis from a disk tango swap, for "
                 "pre-Infinity 'legacy' nodes, or (b) the node is a "
                 "FRU replacement compute for a compute tango swap. "
                 "Either case is grounds for a 'VPD push' of the node's "
                 "serno/partno data to the node (compute) Resume. "
                 "Also, for Infinity chassis tango swap, attempts to do a "
                 "'VPD push' of the node's CHASSIS_TLA_SN serno to the "
                 "Chassis/Midplane Resume if the Resume value is NULL."))
parser.add_argument('-d', '--debug', action='store_true',
                    help='Enable debug output')
parser.add_argument('-r', '--reImage', action='store_true',
                    help='Only pull the system config number and write it to disk')
parser.add_argument('-c', '--chassisTango', action='store_true',
                    help=('Only push the chassis serial number from disk to '
                          'Chassis/Midplane Resume (if and only if the Resume '
                          'value is null). If no serial number is available on '
                          'node disk, it must be provided at the prompt. '
                          'INTERACTIVE COMMAND.'))


def main():
    global args
    global log
    log = init_logging()
    args = parser.parse_args()

    if args.debug:
        log.setLevel(logging.DEBUG)

    try:
        # As part of 7.1.0, USB reimages now run isi_inventory_tool.
        # For Bug 109508, a way to determine whether a S/X200
        # is CTO or SKU was needed. To accomplish this, the reImage
        # flag was added to isi_vpd_pull to only pull the system config
        # number and write it to disk.
        if args.reImage:
            return reimage_pull()

        if args.chassisTango:
            return eeprom_chassis_tango_push()

        if supports_eeprom():
            eeprom_pull()
        elif supports_bmc_vpd():
            bmc_pull()
        elif hal.supportsVmxVpd():
            vmx_pull()
        else:
            return 1

        if bootstrap.isInfinityMotherboard():
            _eeprom_pull_additional_info()

        return 0

    except Exception, e:
        if args.debug:
            raise
        log.error("Error running isi_vpd_pull: %s" % traceback.format_exc())
        return 1

#------------------------------------------------------------------------------
if __name__ == "__main__":
    sys.exit(main())
