#!/usr/bin/env python
#
# This script provides the logic required to transform a 3/4 chassis
# into product, both at initial installation time, as well as during
# a disk tango operation. 
#

# XXX IMPORTANT DEPRECATING FREIGHT TRAINS: Now that we have deprecated
# all 3/4 chassis support, most of this tool is useless and deleted.
# All 3/4 chassis transformation and tango functionality is removed,
# but the CTO conversion functionality is retained.

import re
import os
import sys
import getopt
from syslog import openlog, syslog, LOG_USER, LOG_EMERG, LOG_ALERT, \
    LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG

#
# Globals
#
_g_debug_flag = False
_g_dry_run_flag = False

#
# SKU prefixes that we support
#
VALID_PRODUCT_SKU_PREFIX = '851'

#
# EEPROM key prefix used for legacy data
#
CHAS_VPD_EEPROM_KEY_PREFIX = '$LEGACY_/'

#
# Paths, filenames, etc.
#
CHAS_VPD_PATH = '/etc'
CHAS_SKU_FILENAME = 'isilon_system_config'
CHAS_SERIAL_FILENAME = 'isilon_serial_number'
FCB_VPD_TOOL_PATH = '/usr/bin/isi_hwtools/isi_fcb_vpd_tool'
FSCK_TOOL_PATH = '/sbin/fsck'
MOUNT_TOOL_PATH = '/sbin/mount'
UMOUNT_TOOL_PATH = '/sbin/umount'
DONGLE_PART_PATH = '/dev/ad0s1e'
DONGLE_MOUNT_POINT = '/mnt'
INVENTORY_TOOL_PATH = '/usr/bin/isi_inventory_tool'
DONGLE_SYNC_PATH = '/usr/bin/isi_dongle_sync'

#
# The twenty (20) X200 and S200 SKUs that were defined to be
# able to ship Wingfoot and Blue Flame nodes with 6.5.1.
#
X200_SKUS = [ '851-0112', '851-0113', '851-0114', '851-0115', '851-0116',
              '851-0117', '851-0118', '851-0119', '851-0120', '851-0121',
              '851-0122', '851-0123', '851-0124' ]

S200_SKUS = [ '851-0125', '851-0126', '851-0127', '851-0128', '851-0129',
              '851-0130', '851-0172' ]

#
# The two (2) base chassis SKUs for Belknap based Wingfoot and Blue Flame
#
# NOTE: We never shipped any RocketFuel based WF/BF with 6.5.1, so we only
#       have to deal with these two (2) SKUs.
#
X200_BASE_SKU = '400-0034'
S200_BASE_SKU = '400-0033'

#
# Initialize logging
#
def init_logging():

    openlog('isi_transform_tool', 0, LOG_USER)
    return
    
#
# Post message to stdout and /var/log/messages with the specified priority.
#
def logit(priority=None, msg=None):

    # Map standard syslog priorities into message tags used on stdout
    tag = {
        LOG_EMERG   : 'EMERGENCY',
        LOG_ALERT   : 'ALERT',
        LOG_CRIT    : 'CRITICAL',
        LOG_ERR     : 'ERROR',
        LOG_WARNING : 'WARNING',
        LOG_NOTICE  : 'NOTICE',
        LOG_INFO    : 'INFO',
        LOG_DEBUG   : 'DEBUG',
    } [priority]

    # Post message to stdout with tag
    if tag == 'INFO':
        print '%s: %s' % (tag, msg)
        # LOG_INFO doesn't make it to /var/log/messages up its priority
        priority = LOG_NOTICE
    elif tag != 'DEBUG':
        print '%s: %s' % (tag, msg)
    else:
        if _g_debug_flag is True:
            print '%s: %s' % (tag, msg)
    # Change msg from a list of strings to a string if necessary
    # for syslog call which expects to receive a string.  
    # I.e. the get_cmd_output call for isi_radish returns a list of 
    # strings so the disk's number of blocks can be parsed.  However when
    # isi_radish fails we need to convert the list to a string here.
    msgout = ''
    for line in msg:
        msgout += line

    # Post message to /var/log/messages
    syslog(priority, msgout)

    return

#
# Report this message only if the global debug flag is true
#
def DEBUG(msg=None):

    if _g_debug_flag is True:
        logit(LOG_DEBUG, msg)

    return

#
# Process an error from a call to "procs.get_cmd_output()"
#
def cmd_error(cmd=None, output=None):

    logit(LOG_ERR, 'COMMAND ERROR: "%s" failed' % cmd)

    # If there was output with the failure, display it as well
    if len(output) > 0:
        logit(LOG_ERR, 'OUTPUT FROM COMMAND:')
        logit(LOG_ERR, output)
    
    return

#
# Is the SKU prefix (1st 3 digits) valid?
#
# sku is a string of the form 'XXX-XXXX' (i.e. '851-0073', etc.)
#
def sku_prefix_is_valid(sku=None):

    if sku is None:
        logit(LOG_ERR, 'ARGUMENT ERROR: SKU not specified')
        raise Exception

    if ((sku.find(VALID_PRODUCT_SKU_PREFIX) < 0)):
        logit(LOG_ERR, 
                'ERROR: SKU "%s" does not have a valid prefix ("%s")' %
                (sku, VALID_PRODUCT_SKU_PREFIX))
        return False

    return True

#
# Is the /etc partition on the PATA dongle mounted?
#
def dongle_is_mounted():
    import isi.app.lib.procs as procs

    (error, output) = procs.get_cmd_output('%s | grep %s' % \
        (MOUNT_TOOL_PATH, DONGLE_PART_PATH))
    if error or len(output) == 0:
        # PATA dongle does not appear to be mounted
        mounted = False
    else:
        mounted = True
    return mounted

#
# Mount the /etc partition on the PATA dongle.
#
def mount_dongle():
    import isi.app.lib.procs as procs

    cmd = '%s %s' % (FSCK_TOOL_PATH, DONGLE_PART_PATH)
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return None

    cmd = '%s %s %s' % (MOUNT_TOOL_PATH, DONGLE_PART_PATH, DONGLE_MOUNT_POINT)
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return None

    return DONGLE_MOUNT_POINT

#
# Unmount /etc partition on the PATA dongle
#
def umount_dongle():
    import isi.app.lib.procs as procs

    cmd = '%s %s' % (UMOUNT_TOOL_PATH, DONGLE_MOUNT_POINT)
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return 1

    return 0
                    
#
# Return the specified chassis VPD from the specified location.
#
# type can be 'sku' or 'serial'
# location can be 'disk', 'eeprom' or 'dongle'.
#
def get_chassis_vpd(vpd_type=None, location=None):
    import isi.hw.dongle as hwdongle
    import isi.app.lib.procs as procs

    if vpd_type != 'sku' and vpd_type != 'serial':
        logit(LOG_ERR, 'ARGUMENT ERROR: "%s" is not a valid VPD type '
               '("%s" or "%s")' % (vpd_type, 'sku', 'serial'))
        raise Exception

    if location != 'disk' and location != 'eeprom' and location != 'dongle':
        logit(LOG_ERR, 'ARGUMENT ERROR: "%s" is not a valid SKU location '
               '("%s", "%s" or "%s")' % (location, 'disk', 'eeprom', 'dongle'))
        raise Exception
    
    if location == 'eeprom':
        if not hwdongle.eeprom_supported():
            logit(LOG_INFO, 'EEPROM is not supported on this chassis')
            return None
        if not hwdongle.eeprom_present():
            logit(LOG_INFO, 'EEPROM is not present on this chassis')
            return None
    elif location == 'dongle':
        if not hwdongle.dongle_supported():
            logit(LOG_INFO, 'PATA dongle is not supported on this chassis')
            return None
        if not hwdongle.dongle_present():
            logit(LOG_INFO, 'PATA dongle is not present on this chassis')
            return None

    if vpd_type == 'sku':
        vpd_type_str = 'SKU'
    elif vpd_type == 'serial':
        vpd_type_str = 'serial number'

    if location == 'disk':
        location_str = 'on disks'
    elif location == 'eeprom':
        location_str = 'in EEPROM'
    elif location == 'dongle':
        location_str = 'on PATA dongle'

    if vpd_type == 'sku':
        if location == 'disk':
            filename = (CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME)
        elif location == 'dongle':
            filename = (DONGLE_MOUNT_POINT + \
                        (CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME))
        elif location == 'eeprom':
            filename = None
            eeprom_grep_string = CHAS_SKU_FILENAME
    elif vpd_type == 'serial':
        if location == 'disk':
            filename = (CHAS_VPD_PATH + '/' + CHAS_SERIAL_FILENAME)
        elif location == 'dongle':
            filename = (DONGLE_MOUNT_POINT + \
                        (CHAS_VPD_PATH + '/' + CHAS_SERIAL_FILENAME))
        elif location == 'eeprom':
            filename = None
            eeprom_grep_string = CHAS_SERIAL_FILENAME

    if location == 'dongle':
        dongle = mount_dongle()
        if dongle is None:
            logit(LOG_INFO, 'Unable to mount PATA dongle partition')
            return None

    # See if the desired file even exists
    no_file = False
    if location == 'disk':
        if vpd_type == 'sku' and not disks_have_chassis_sku():
            logit(LOG_ERR, 'Disks do not contain a chassis SKU')
            no_file = True
        elif vpd_type == 'serial' and not disks_have_chassis_serial():
            logit(LOG_ERR, 'Disks do not contain a chassis serial number')
            no_file = True
    elif location == 'dongle':
        if vpd_type == 'sku' and not dongle_has_chassis_sku():
            logit(LOG_INFO, 'PATA dongle does not contain a chassis SKU')
            no_file = True
        elif vpd_type == 'serial' and not dongle_has_chassis_serial():
            logit(LOG_INFO, 'PATA dongle does not contain a chassis serial'
                    'number')
            no_file = True

    # If the file we're after doesn't exist, we're done
    if no_file:
        if location == 'dongle':
            if umount_dongle() != 0:
                logit(LOG_INFO, 'Unable to umount PATA dongle partition')
        return None

    if location == 'disk' or location == 'dongle':
        cmd = 'cat %s' % filename
    elif location == 'eeprom':
        cmd = '%s dump | grep %s' % (FCB_VPD_TOOL_PATH, eeprom_grep_string)
        
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        # If dongle, we have to clean up before we leave
        if location == 'dongle':
            if umount_dongle() != 0:
                logit(LOG_INFO, 'Unable to umount PATA dongle partition')
        return None

    if len(output) == 0:
        DEBUG('"%s" resulted in no %s' % (cmd, vpd_type_str))
        # If dongle, we have to clean up before we leave
        if location == 'dongle':
            if umount_dongle() != 0:
                logit(LOG_INFO, 'Unable to umount PATA dongle partition')
        return None

    # Done with dongle filesystem now, clean up
    if location == 'dongle':
        if umount_dongle() != 0:
            logit(LOG_INFO, 'Unable to umount PATA dongle partition')
            return None

    if vpd_type == 'sku':
        match_key = 'sku'
        if location == 'disk' or location == 'dongle':
            p = re.compile('^(?P<sku>[0-9]{3}-[0-9]{4}-[0-9]{2}$)')
        elif location == 'eeprom':
            p = re.compile('^.*\[\'(?P<sku>[0-9]{3}-[0-9]{4}-[0-9]{2})')
    elif vpd_type == 'serial':
        match_key = 'serial'
        #
        # Serial number formats vary by platform
        #
        # Node Type             Prefix   Serial Number Format
        # ---------             ------   --------------------
        # Rainier                N/A         YYWWXXXXM
        # Ullr/Fuego Accelerator "A"        AYYWWXXXXM
        # Annapurna Accelerator  "A"       AYYWWXXXXXM
        # Graham                 "G"       GYYWWXXXXXM
        # Mauna Loa              "M"       MYYWWXXXXXM
        # Racer-X                "R"       RYYWWXXXXXM
        #
        # Note: This code does not deal with EX chassis VPD so there
        #       is no regular expressions that handle the 'D' prefix.
        #
        if location == 'disk' or location == 'dongle':
            p = re.compile('^(?P<serial>[AGgMmRr](0[3-9])([0-9]{2})' \
                           '([0-9]{5})[SsLlJj]$)')
        elif location == 'eeprom':
            # Only Annapurna, Graham, Mauna Loa and Racer-X have
            # EEPROM devices
            p = re.compile('^.*\[\'(?P<serial>[AGgMmRr](0[3-9])' \
                           '([0-9]{2})([0-9]{5})[SsLlJj])')

    vpd = None
    for line in output:
        m = p.match(line)
        if m:
            vpd = m.group(match_key)
            if vpd is not None:
                break

    if vpd is None:
        logit(LOG_INFO, 'Unable to locate chassis %s %s' % 
                (vpd_type_str, location_str))
        return None

    return vpd

#
# Return (extract) the part number from specified SKU
#
# sku is a string of the form 'XXX-XXXX' (i.e. '851-0073', etc.)
#
def extract_part_number_from_sku(sku=None):

    if sku is None:
        logit(LOG_ERR, 'ARGUMENT ERROR: SKU not specified')
        raise Exception

    p = re.compile('^(?P<part_number>[0-9]{3}-[0-9]{4})')
    m = p.match(sku)
    if m:
        part_number = m.group('part_number')

    if part_number is None:
        logit(LOG_ERR, 'Unable to locate part number in "%s"' % sku)
        return None

    return part_number

#
# Return (extract) the 'TAB' (revision) level from specified SKU
#
# sku is a string of the form 'XXX-XXXX' (i.e. '851-0073', etc.)
#
def extract_tab_level_from_sku(sku=None):

    if sku is None:
        logit(LOG_ERR, 'ARGUMENT ERROR: SKU not specified')
        raise Exception

    if not sku_prefix_is_valid(sku):
        return None

    p = re.compile('^[0-9]{3}-[0-9]{4}-(?P<tab>[0-9]{2})')
    m = p.match(sku)
    if m:
        tab = m.group('tab')

    if tab is None:
        logit(LOG_ERR, 'Unable to locate TAB level in "%s"' % sku)
        return None

    return tab
 
#
# Write the specified chassis SKU to the specified location.
#
# sku is a string of the form 'XXX-XXXX' (i.e. '851-0073', etc.)
# location can be 'disk' or 'eeprom'.
#
def write_chassis_sku(sku=None, location=None):
    import isi.app.lib.procs as procs

    if _g_dry_run_flag is True:
        print 'Dry run - bypass writing chassis SKU'
        return 0

    if sku is None:
        logit(LOG_ERR, 'ARGUMENT ERROR: SKU not specified')
        raise Exception

    if location != 'disk' and location != 'eeprom':
        logit(LOG_ERR, 'ARGUMENT ERROR: "%s" is not a valid SKU location '
               '("%s" or "%s")' % (location, 'disk', 'eeprom'))
        raise Exception

    if location == 'disk':
        cmd = 'echo %s > %s' % (sku, (CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME))
    elif location == 'eeprom':
        eeprom_key = (CHAS_VPD_EEPROM_KEY_PREFIX + \
                        (CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME))
        cmd = '%s write %s %s' % (FCB_VPD_TOOL_PATH, eeprom_key, sku)
        
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return 1
    
    return 0

#
# Push VPD from disks to chassis (eeprom/PATA dongle). 
#
def push_vpd_from_disk_to_chassis():
    import isi.app.lib.procs as procs

    if _g_dry_run_flag is True:
        print 'Dry run - bypass pushing VPD from disk to chassis'
        return 0

    cmd = '%s -p' % DONGLE_SYNC_PATH
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return 1
    
    return 0
    
#
# Sync the VPD from the chassis (eeprom/PATA dongle) to the disks.
#
def sync_vpd_from_chassis_to_disk():
    import isi.app.lib.procs as procs

    if _g_dry_run_flag is True:
        print 'Dry run - bypass pulling VPD from chassis to disk'
        return 0

    cmd = '%s' % DONGLE_SYNC_PATH
    (error, output) = procs.get_cmd_output(cmd)
    if error:
        cmd_error(cmd, output)
        return 1
    
    return 0

#
# Do the disks have a chassis SKU?
#
def disks_have_chassis_sku():

    if os.path.exists((CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME)):
        return True

    return False

#
# Do the disks have a chassis serial number?
#
def disks_have_chassis_serial():

    if os.path.exists((CHAS_VPD_PATH + '/' + CHAS_SERIAL_FILENAME)):
        return True

    return False

#
# Does the PATA dongle have a chassis SKU?
#
def dongle_has_chassis_sku():

    if not dongle_is_mounted():
        DEBUG('PATA dongle filesystem is not mounted')
        raise Exception

    if os.path.exists((DONGLE_MOUNT_POINT + \
                        (CHAS_VPD_PATH + '/' + CHAS_SKU_FILENAME))):
        return True

    return False

#
# Does the PATA dongle have a chassis serial number?
#
def dongle_has_chassis_serial():

    if not dongle_is_mounted():
        DEBUG('PATA dongle filesystem is not mounted')
        raise Exception

    if os.path.exists((DONGLE_MOUNT_POINT + \
                        (CHAS_VPD_PATH + '/' + CHAS_SERIAL_FILENAME))):
        return True

    return False

#
# Does the chassis contain SSD drives?
#
def chassis_has_ssd():
    import isi.hw.bay as hwbay

    has_ssd = False
    nbays = hwbay.getCounts(0)[0]
    for bay in range (1, nbays):
        if hwbay.isSsd(bay):
            has_ssd = True
            break

    if has_ssd:
        logit(LOG_INFO, 'SSD drive found in bay %d' % bay)
    else:
        logit(LOG_INFO, 'No SSD drives found in chassis')
        
    return has_ssd

#
# Is chassis SKU in sync (disks match EEPROM)?
#
def chassis_sku_in_sync():

    logit(LOG_INFO, 'Checking if chassis SKU is in sync')
    eeprom_sku = get_chassis_vpd('sku', 'eeprom')
    if eeprom_sku is None:
        logit(LOG_ERR, 'ERROR: Unable to locate chassis SKU in EEPROM')
        return False

    hdd_sku = get_chassis_vpd('sku', 'disk')
    if hdd_sku is None:
        logit(LOG_ERR, 'ERROR: Unable to locate chassis SKU on disks')
        return False

    logit(LOG_INFO, 'Chassis SKU read from EEPROM is "%s"' % eeprom_sku)
    logit(LOG_INFO, 'Chassis SKU read from disks is "%s"' % hdd_sku)

    if hdd_sku != eeprom_sku:
        logit(LOG_ERR, 'ERROR: Chassis SKU on disk and in EEPROM do not match '
                '(disk has "%s", EEPROM has "%s")' % (hdd_sku, eeprom_sku))
        return False

    return True

#
# Check if chassis requires conversion. A chassis requires conversion 
# when it is one of the nineteen (19) Wingfoot or Blue Flame SKU based 
# chassis that were shipped with 6.5.1. However, starting with 6.5.2, 
# all WF/BF nodes will be built using CTO, therefore, we need to locate 
# each of the nodes that were built as SKU based products and convert 
# them to use the CTO (receipt) based process. 
#
def needs_conversion():

    # Make sure we're starting with a node that's in a good state
    if not chassis_sku_in_sync():
        logit(LOG_ERR, 'Chassis SKU not in sync between disks and EEPROM')
        return 0

    # Now that we're sure they are in sync, it's quicker to read SKU from disk
    hdd_sku = get_chassis_vpd('sku', 'disk')
    if hdd_sku is None:
        # Technically redundant because of call to chassis_sku_in_sync()
        logit(LOG_ERR, 'ERROR: Unable to locate chassis SKU on disks')
        return 0

    logit(LOG_INFO, 'Chassis SKU read from disks is "%s"' % hdd_sku)

    # Ignore TAB level when searching for product SKUs
    product_sku = extract_part_number_from_sku(hdd_sku)
    if product_sku is None:
        logit(LOG_ERR, 'Unable to locate P/N in product SKU "%s"' % product_sku)
        return 0

    # Check both X200 and S200 lists
    rc = 0
    for sku in X200_SKUS:
        if sku == product_sku:
            rc = 1
            break
    # Wasn't an X200, now check S200
    if rc == 0:
        for sku in S200_SKUS:
            if sku == product_sku:
                rc = 1
                break

    return rc

#
# Convert this SKU-based node into a CTO node by transforming the
# chassis product SKU into the appropriate CTO base chassis SKU.
#
# Intended for (manual) use when one (1) of the nineteen (19) Wingfoot
# or Blue Flame product SKUs are encountered in the field.
#
def convert():
    import isi.hw.hal as hal
    import isi.app.lib.procs as procs

    # Make sure everything is copasetic before we begin
    if not needs_conversion():
        logit(LOG_NOTICE, 'Node does not require conversion')
        return 1

    hdd_sku = get_chassis_vpd('sku', 'disk')
    if hdd_sku is None:
        # Technically redundant because of call to needs_conversion()
        logit(LOG_ERR, 'ERROR: Unable to locate chassis SKU on disks')
        return 1

    logit(LOG_INFO, 'Chassis SKU read from disks is "%s"' % hdd_sku)

    # For purposes of locating the nodes, we ignore the TAB level
    product_pn = extract_part_number_from_sku(hdd_sku)
    if product_pn is None:
        logit(LOG_ERR, 'Unable to locate P/N in product SKU "%s"' % hdd_sku)
        return 1

    # Translate from product SKU to base chassis SKU for CTO
    base_pn = None
    for sku in X200_SKUS:
        if sku == product_pn:
            base_pn = X200_BASE_SKU
            break

    if base_pn is None:
        for sku in S200_SKUS:
            if sku == product_pn:
                base_pn = S200_BASE_SKU
                break

    if base_pn is None:
        logit(LOG_ERR, 'Unable to convert "%s" to base chassis P/N' % 
            product_pn)
        return 1

    # Grab the TAB level of the product SKU
    tab = extract_tab_level_from_sku(hdd_sku)
    if tab is None:
        logit(LOG_ERR, 'ERROR: Unable to extract TAB level from "%s"' % hdd_sku)
        return 1

    logit(LOG_INFO, 'TAB level of product is "%s"' % tab)

    # Merge tab level of product into base chassis SKU
    base_chassis_sku = base_pn + '-' + tab

    logit(LOG_INFO, 'Writing base chassis SKU "%s" to disks' % base_chassis_sku)
    if write_chassis_sku(base_chassis_sku, 'disk') != 0:
        logit(LOG_ERR, 'Unable to write base chassis SKU ("%s") to disks' %
            base_chassis_sku)
        return 1

    # Once we put the new SKU on the disks, we need to generate
    # hardware capabilities and attributes and kick HAL before
    # we write the VPD to the chassis
    if _g_dry_run_flag is True:
        print 'Dry run - bypass isi_inventory_tool --reInit'
    else:
        logit(LOG_INFO, 'Running isi_inventory_tool --reInit')
        cmd = '%s --reInit' % INVENTORY_TOOL_PATH
        output = procs.get_cmd_output(cmd)[1]
        # Ignore the failure we're sure to get since we know the
        # chassis does not yet have all of its CTO information
        # (receipt, softAVL, etc.)
        for lines in output:
            print lines

    if _g_dry_run_flag is True:
        print 'Dry run - bypass HAL re-initialization'
    else:
        logit(LOG_INFO, 'Re-initializing HAL')
        if hal.reInitialize() != 0:
            logit(LOG_ERR, 'HAL re-initialization failed')
            return 1

    logit(LOG_INFO, 'Pushing VPD from disks into chassis')
    if push_vpd_from_disk_to_chassis() != 0:
        logit(LOG_ERR, 'Unable to push VPD from disks into chassis')
        return 1

    logit(LOG_INFO, 'Syncing VPD from chassis to disks')
    if sync_vpd_from_chassis_to_disk() != 0:
        logit(LOG_ERR, 'Unable to sync VPD from chassis to disks')
        return 1

    if not chassis_sku_in_sync():
        logit(LOG_ERR, 'Chassis SKU not in sync between disks and EEPROM')
        return 1

    logit(LOG_NOTICE, 'CTO conversion completed successfully')

    logit(LOG_WARNING, 'CTO conversion has caused the chassis SKU to change.')
    logit(LOG_WARNING, 'Changing the chassis SKU requires a reboot before ')
    logit(LOG_WARNING, 'the change will take effect. Please reboot as soon')
    logit(LOG_WARNING, 'as possible!')

    return 0

#
# Print help 
#
# error is a string that will be printed along with the usage message
#
def usage(error=None):
    if error:
        print 'ERROR: %s' % error.capitalize()

    print 'Usage: %s [-h,--help] [-d,--debug]\n' \
          '                            [-z,--convert] [-x,--dryrun]' % \
        sys.argv[0]
    print ''
    print '      -h,--help       Show this message'
    print '      -d,--debug      Enable debugging messages'
    print '      -z,--convert    Convert SKU-based node to CTO node'
    print '      -x,--dryrun     Dry run of action. Use with -i, -t, -r & -z'

    return 1

#
# Main program
#
def main(argv=None):

    result = -1

    if argv is None:
        argv = sys.argv

    try:
        (opts, args) = getopt.getopt(argv[1:], 'hdzx',
        ['help', 'debug', 'convert', 'dryrun' ])

    except getopt.GetoptError, e:
        usage(str(e))
        sys.exit(1)

    if args:
        usage('Unexpected arguments: %s' % ' '.join(args))
        sys.exit(1)

    init_logging()

    # So debug option can appear anywhere in the command options
    globals() ['_g_debug_flag'] = False
    globals() ['_g_dry_run_flag'] = False
    for (opt, _) in opts:
        if opt in ('-d', '--debug'):
            globals() ['_g_debug_flag'] = True
        if opt in ('-x', '--dryrun'):
            globals() ['_g_dry_run_flag'] = True

    if _g_dry_run_flag is True:
        print 'Dry run starting...'

    for (opt, _) in opts:
        if opt in ('-h', '--help'):
            result = usage()
        elif opt in ('-z', '--convert'):
            result = convert()

    if _g_dry_run_flag is True:
        print 'Dry run complete. No actions taken.'

    if result < 0:
        result = usage()

    sys.exit(result)

if __name__ == '__main__':
    sys.exit(main())

# vim: et sts=4 sw=4
