#!/usr/local/bin/python
       
# Copyright C 2001-2011 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.
#
#####
#
#   Script to change HEAD system configuration and/or serial numbers.
#
#####
# XXX DEPRECATING PLATFORMS: NB: Do we even need this script anymore?
# XXX Also, check if any internal OneFS callers/consumers.
# XXX NB: StevenS says he *thinks* that this is still used, we need to
# XXX do our homework and due diligence.
# XXX NB: StevenS mentioned that there is a lot of duplicate/re-used
# XXX code over in ui/shell/CfgValidation (ACS) to validate serial
# XXX number (formats) and we should / could move this to a common
# XXX place. (See Also my own comments in etc/rc.d/isi_create_lni_xml.)
# XXX NB: I *really* (REALLY) don't want to "fix" lib.sysconfig to work.
# XXX Even if that means making sure the REGEX et al used here continue
# XXX to work -- if I don't HAVE to, because this isi_update_serialno
# XXX script is UNNEEDED, then I don't WANT to.
# XXX NB: Even if this script is "still used," nonetheless we're getting
# XXX rid of deprecated hardware support APIs, e.g. Vitesse related code
# XXX and APIs for DONs - so anything having to do with chasnOwnerSerialno,
# XXX etc., is going to be surgically snipped.

import os
import sys
import re
import getopt

import isi.app.lib.procs as procs
import isi.hw.check.lib.sysconfig as sysconfig
import isi.hw.hal as hal
import isi.hw.version as hwver

verbose = False

isilon_system_config = '/etc/isilon_system_config'
isilon_system_serial = '/etc/isilon_serial_number'
isi_dongle_sync      = '/usr/bin/isi_dongle_sync'
isi_vitutil          = '/usr/bin/isi_hwtools/isi_vitutil'

def usage(code):
    print >> sys.stderr, 'usage: isi_update_serialno [-h] [-v]'
    print >> sys.stderr, "\t-h:  help"
    print >> sys.stderr, "\t-v:  verbose"
    sys.exit(code)

#
#    Prompt user for the new serial number.
#
#    Loop until the user specifies a valid serial number
#    or enters <return> to keep the current serial number.
#
#    Legacy serial numbers have the following format:
#
#                                 [A]YYWWXXXX[SsLlJjPp]         
#
#                                  N/A   = Rainier node (no prefix)
#                                  A     = Accelerator node
#                                  YY    = year
#                                  WW    = week
#                                  XXXX  = 4-digit per-platform unique id
#                                  XXXXX = 5-digit per-platform unique id
#                                  Ss    = Sanmina
#                                  Ll    = Flextronix
#                                  Jj    = Jabil
#                                  Pp    = Prototype (Built in Engineering)
#
# Examples of node legacy serial number formats:
#
# Accelerator node : 'A'     AYYWWXXXXM
#
# Node SN trailing CM indicator 'M': S=Sanmina, L=Solectron (Flextronics)
#                                  : J=Jabil, P=Prototype (Engineering)
# 
#    New serial numbers have the following format:
#
#       SFCGG-MMYYWW-XXXX
#       S  = "Serial number", always 'S'
#       F  = Family: 
#            X: X-series   (incl. Wingfoot)
#            S: S-series   (incl. Blueflame)
#            N: NL-series
#       C  = Class:
#            2: 2U
#            4: 4U
#       GG = Generation: 
#            00: 1st Gen (X or S)
#       MM = Manufacturer Code: Numeric: (NOT "Month"!!)
#            These are the same the as PCA component codes:
#            10: Sanmina 
#            20: Flextronics (Austin)
#            21: Flextronics (Shenzhen)
#            22: Flextronics (Services)
#            30: Jabil       (Memphis)
#            31: Jabil       (Wuxi)
#            40: Isilon      (Plymouth) (Internal, Prototypes)
#            41: Isilon      (Seattle)  (Internal, Prototypes)
#       YY = Year
#       WW = Week
#     XXXX = 4-digit serno; Resets every week
#
# Examples of node new serial number formats:
#
# Wingfoot node    :         SX200-MMYYWW-XXXX
# Blue Flame node  :         SS200-MMYYWW-XXXX
#                                           
# From Section 7: SERIAL NUMBER STRUCTURE for EMC Designed products
# Positions   Field Name                      Presence
#       1-3   Supplier/Vendor Identifier      Required - documented in EMC
#                                             document #999-999-323
#       4-5   Component Code                  Required, defaults to 00 *
#       6-7   Date Code, Year of manufacture  Required
#       8-9   Date Code, Week of manufacture  Required, based on EMC fiscal year
#     10-14   Instance Identifier             Required, resets at supplier
#                                             option to 00001 each production
#                                             week, or continues to increment

def prompt_for_serialno(chassis, cur_serialno):
    global verbose
    regexes = [
        sysconfig._NODE_SERIAL_REGEX('','',4),
        sysconfig._NODE_SERIAL_REGEX('[A]','',4),
        sysconfig._NODE_SERIAL_REGEX('[A]','',5),
        sysconfig._BONNE_NODE_SERIAL_REGEX('[NnSsXx]', '[24]', '\d{2}'),
        sysconfig._EMC_NODE_SERIAL_REGEX('\w{3}','\w{2}'),
    ]
    reg_serial = '|'.join(regexes)
    regx_serial = re.compile(reg_serial)
    prompt = 'Chassis %d: Enter new serial number [current %s] > ' \
              % (chassis, cur_serialno)

    while True:
        new_serialno = raw_input(prompt)

        if regx_serial.match(new_serialno) or not new_serialno:
            break
        else:
            print '\nError:  Invalid serial number "%s"' % new_serialno
            print 'Valid legacy serial numbers follow the following formats:'
            print ''
            print '    Node Type             Prefix   Serial Number Format'
            print '    ---------             ------   --------------------'
            print '    Annapurna Accelerator  "A"       AYYWWXXXXXM'
            print ''
            print '                           Where:'
            print '                                 YY    = Year'
            print '                                 WW    = Week'
            print '                                 XXXXX = Unique ID'
            print '                                 M     = Manufacturer Code'
            print ''
            print '                           Manufacturer Codes are:'
            for (key, val) in sysconfig._CM_NODE_CODES.iteritems():
                print '                                 %s: %s' % (key, val)
            print ''
            print '    Modern Serial Number Format'
            print '    ---------------------------'
            print '    SFCGG-MMYYWW-XXXX'
            print ''
            print '    Where:'
            print '        S  = "Serial number", always \'S\''
            print '        F  = Family:' 
            for (key, val) in sysconfig._FAM_NODE_CODES.iteritems():
                print '             %s: %s' % (key, val)
            print '        C  = Class:'
            for (key, val) in sysconfig._CLS_NODE_CODES.iteritems():
                print '             %s: %s' % (key, val)
            print '        GG = Generation:' 
            for (key, val) in sysconfig._GEN_NODE_CODES.iteritems():
                print '             %s: %s' % (key, val)
            print '        MM = Manufacturer Code:'
            print '              - Numeric: (NOT "Month"!!)'
            print '              - These are the same as the'
            print '                PCA component codes:'
            for (key, val) in sysconfig._CM_LOCATION_CODES.iteritems():
                print '                  %s: %s' % (key, val)
            print '        YY = Year'
            print '        WW = Week'
            print '      XXXX = 4-digit serno; Resets every'
            print '             week.'
            print ''
            print '    EMC PSNT Serial Number Format'
            print '    ------------------------'
            print '    VVVPPYYWWXXXXX'
            print ''
            print '    Where:'
            print '       VVV = Supplier/Vendor Identifier'
            print '        PP = Component Code'
            print '        YY = Year'
            print '        WW = Week'
            print '     XXXXX = 5-digit Instance Identifier; Resets every'
            print '             week.'


    if verbose:
        print 'current serial number %s  new serial number %s' \
               % (cur_serialno, new_serialno)

    return new_serialno


#
#    Prompt user for the new configuration number.
#
#    Loop until the user specifies a valid configuration number
#    or enters <return> to keep the current configuration number.
#
#    System configuration numbers have the following format:
#
#            XXX-XXXX-XX
#
def prompt_for_configno(chassis, cur_configno):
    global verbose
    regexes = [
        sysconfig._CONFIG_REGEX('',''),
        sysconfig._BASECHASSIS_NODE_CONFIG_REGEX,
    ]
    configno_format = sysconfig._BASECHASSIS_NODE_CONFIG_FMT
    reg_config = '|'.join(regexes)
    regx_config = re.compile(reg_config)
    prompt = ('Chassis %d: Enter new configuration number (%s) '
             '[current %s] > ' % (chassis, configno_format, cur_configno))

    while True:
        new_configno = raw_input(prompt)

        if regx_config.match(new_configno) or not new_configno:
            break
        else:
            print '\nError:  Invalid configuration number "%s"' % new_configno
            print 'Valid configuration numbers follow the following format:'
            print ''
            print 'Isilon Legacy Config Number'
            print ' XXX-XXXX-XX'
            print ''
            print 'EMC PSNT Part Number'
            print ' XXX-XXX-XXX'

    if verbose:
        print 'current configuration number %s  new configuration number %s' \
                % (cur_configno, new_configno)

    return new_configno


def main(args):
    global verbose

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hv')
    except:
        usage(1)

    #
    #    Parse the command line arguments.
    #
    for opt, arg in opts:
        if opt == '-h':
            usage(0)
        if opt == '-v':
            verbose = True

    #
    #   Get the chassis counts for this node.
    #
    chassis_count = hal.getChassisCount()
    chassis_total_up = hal.getActiveChassisCount()
    if chassis_count != chassis_total_up:
        print "Warning:  not all chassis' are up (up %d total %d)" % \
              (chassis_total_up, chassis_count)
    if verbose:
        print "Chassis count %d  up %d" % (chassis_count, chassis_total_up)

    #
    #   Prompt the user for possible changes to the HEAD chassis config number.
    #
    sync_the_dongle   = False
    head_old_configno = hal.getChassisConfigNumber(0)
    head_new_configno = prompt_for_configno(0, head_old_configno)
    if verbose:
        print "HEAD System Config Number:  old %s new %s" % \
              (head_old_configno, head_new_configno)
    if head_new_configno:
        print 'Changing HEAD system configuration number from "%s" to "%s"' % \
              (head_old_configno, head_new_configno)
        cmd = "echo %s > %s" % (head_new_configno, isilon_system_config)
        (error, output) = procs.get_cmd_output(cmd)
        if error:
             print "Writing system configuration number to %s failed" % \
                   isilon_system_config
             sys.exit(1)
        else:
             sync_the_dongle = True

    #
    #   Prompt the user for possible changes to the HEAD chassis serial number.
    #
    head_old_serialno = hal.getChassisSerialNumber(0)
    head_serialno     = head_old_serialno
    head_new_serialno = prompt_for_serialno(0, head_old_serialno)
    if verbose:
        print "HEAD Serial Number:  current %s new %s" % \
              (head_old_serialno, head_new_serialno)
    if head_new_serialno:
        print 'Changing HEAD serial number from "%s" to "%s"' % \
              (head_old_serialno, head_new_serialno)
        cmd = "echo %s > %s" % (head_new_serialno, isilon_system_serial)
        (error, output) = procs.get_cmd_output(cmd)
        if error:
             print "Writing serial number to %s failed" % \
                   isilon_system_serial
             sys.exit(1)
        else:
             sync_the_dongle = True
             head_serialno = head_new_serialno

    if sync_the_dongle == True:
        print "*****************************************************" \
            "***********************"
        print "WARNING: Changing the system configuration and/or " \
            "serial number requires"
        print "         a reboot before the change(s) will take effect. " \
            "Please reboot as "
        print "         soon as possible!"
        print "*****************************************************" \
            "***********************"
        if verbose == True:
            print "Syncing the dongle....."
        cmd = "%s -p" % isi_dongle_sync
        (error, output) = procs.get_cmd_output(cmd)
        if error:
            print "Error:  writing changes to the dongle failed"
            sys.exit(1)

    return 0


if __name__ == '__main__':

    status = main(sys.argv)

    sys.exit(status)

