#! /usr/bin/env python

# Copyright C 2008-2011 by Isilon Systems, Inc. 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 node system configuration, serial numbers, and
#    install node-specific CTO receipts.
#

import getopt
import os
import os.path
import re
import sys

import isi.hw.check.lib.cto as cto


#########################################################################
### MOVED CONTENTS OF isi.hw.check.mfg.options here, for now

import isi.hw.check.lib.args as argslib

def get_options_action(usage=None):
    # Options that perform an action and exit
    options = {
        'help':
        {'opts'         : ['h', 'help'],
         'func'         : argslib.help_func(usage),
         'help-desc'    : 'Show this text',
         },
        
        }
    return options

def get_options_remote():
    # Options that may be specified remotely (or locally)
    options = {
        'ignore_id_failures':
        {'opts'         : ['i'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'restricted'   : False,
         'remote'       : True,
         'help-desc'    : 'Ignore failure in id tests',
         },
        
        'skip_identify':
        {'opts'         : ['s'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'restricted'   : False,
         'remote'       : True,
         'help-desc'    : 'Skip id tests',
         },
        
        'admin_mode':
        {'opts'         : ['a'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'restricted'   : False,
         'remote'       : True,
         'help-desc'    : 'Admin mode; allow access to all menu tests',
         },
        
        'modules_to_run':
        {'opts'         : ['m:'],
         'default'      : [],
         'func_attrs'   : argslib.modules_to_run_func(),
         'restricted'   : False,
         'remote'       : True,
         'help-desc'    : 'Run only the given module',
         'help-arg'     : 'MODULE',
         },
        }
    return options

def get_options_non_remote():
    # Options that may NOT be specified remotely (only locally)
    options = {
        'anyserial':
        {'opts'         : ['anyserial'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Allow non-standard serial-number formats',
         },
        
        'logdir':
        {'opts'         : ['l:'],
         'default'      : './logs/',
         'func'         : str,
         'help-desc'    : 'Local directory for log files (defaults to ./logs/)',
         'help-arg'     : 'LOGDIR',
         },
        
        'no_remote_logging':
        {'opts'         : ['n'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Disable remote logging (forced if -m and -s set)',
         },
        
        'newserial':
        {'opts'         : ['newserial'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Force reading new serial/config numbers',
         },
        
        'newconfig':
        {'opts'         : ['newconfig'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Force reading new system config number',
         },

        'newfirmware':
        {'opts'         : ['newfirmware'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Force new firmware',
         },
        
        'newlocation':
        {'opts'         : ['newlocation'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Force reading new location number',
         },
        
        'do_text':
        {'opts'         : ['t'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Prompt for text at start of run',
         },
        
        'no_remote_opts':
        {'opts'         : ['no-remote-opts'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Ignore remote options',
         },
        
        'ignore_stats':
        {'opts'         : ['ignore-stats'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : 'Ignore stat failures',
         },
        }
    return options

def get_options_cmdb():
    # Options that are CTO / CMDB related
    options = {
        'cmdb_method':
        {'opts'         : ['cmdb-method='],
         'default'      : None, # Use CMDB default
         'func'         : str,
         'help-desc'    : 'Specify access method',
         'help-arg'     : 'METHOD',
         },
        
        'cmdb_ip':
        {'opts'         : ['cmdb-ip='],
         'default'      : None, # Use CMDB default
         'func'         : str,
         'help-desc'    : 'Specify server IP address',
         'help-arg'     : 'IP',
         },
        
        'cmdb_user':
        {'opts'         : ['cmdb-user='],
         'default'      : None, # Use CMDB default
         'func'         : str,
         'help-desc'    : 'Specify user account',
         'help-arg'     : 'USER',
         },
        
        'cmdb_local':
        {'opts'         : ['cmdb-local='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify local directory for CMDB files',
         'help-arg'     : 'LOCAL',
         },
        }
    return options
        
def get_options_hidden():
    # Options that are hidden (non-advertised)
    options = {
        'debug_level':
        {'opts'         : ['debug-level='],
         'default'      : 0,
         'func'         : int,
         'help-desc'    : None,
         },
        
        'fake_stats_dir':
        {'opts'         : ['fake-stats='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : None,
         },

        'async':
        {'opts'         : ['async'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : None,
         },

        'use_cached':
        {'opts'         : ['use-cached'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : None,
         },
        
        'skip_inventory':
        {'opts'         : ['skip-inventory'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : None,
         },
        
        'chassisconfig':
        {'opts'         : ['chassisconfig'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : None,
         },

        'diskscrub_full':
        {'opts'         : ['diskscrub-full'],
         'default'      : False,
         'func'         : argslib.true_func(),
         'help-desc'    : None,
        },

        'diskscrub_mult':
        {'opts'         : ['diskscrub-mult='],
         'default'      : None,
         'func'         : int,
         'help-desc'    : None,
        },
        }
    return options

def get_options_node():
    options = {
        # --node-serial is currently only supported in mfg.config.cto
        'node_serial':
        {'opts'         : ['node-serial='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify node serial number',
         'help-arg'     : 'SERIAL',
         },
        
        # --node-config is currently only supported in mfg.config.cto
        'node_config':
        {'opts'         : ['node-config='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify node system config number',
         'help-arg'     : 'CONFIG',
         },

        'bootflash_drives':
        {'opts'         : ['bootflashdrives='],
         'default'      : None, # None = Use internal defaults
         'func'         : int,
         'help-desc'    : None,
         },

        'bootflash_reads':
        {'opts'         : ['bootflashreads='],
         'default'      : None, # None = Use internal defaults
         'func'         : int,
         'help-desc'    : None,
         },

        'bootflash_wipes':
        {'opts'         : ['bootflashwipes='],
         'default'      : None, # None = Use internal defaults
         'func'         : int,
         'help-desc'    : None,
         },

        'bootflash_writes':
        {'opts'         : ['bootflashwrites='],
         'default'      : None, # None = Use internal defaults
         'func'         : int,
         'help-desc'    : None,
         },
        }
    return options

def get_options_cto():
    options = {
        # --cto-order is currently only supported in mfg.config.cto
        'cto_order':
        {'opts'         : ['cto-order='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify order number',
         'help-arg'     : 'ORDER',
         },
        }
    return options

def get_options_net():
    options = {
        'net_interface':
        {'opts'         : ['net-interface='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify network interface',
         'help-arg'     : 'INTERFACE',
         },
        
        'net_address':
        {'opts'         : ['net-address='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify network IP address',
         'help-arg'     : 'IP',
         },
        
        'net_netmask':
        {'opts'         : ['net-netmask='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify network netmask',
         'help-arg'     : 'NETMASK',
         },
        
        'net_gateway':
        {'opts'         : ['net-gateway='],
         'default'      : None,
         'func'         : str,
         'help-desc'    : 'Specify network gateway',
         'help-arg'     : 'GATEWAY',
         },
        }
    return options

def get_options(usage=None):
    options = {}
    options.update(get_options_action(usage))
    options.update(get_options_remote())
    options.update(get_options_non_remote())
    options.update(get_options_cmdb())
    options.update(get_options_hidden())
    options.update(get_options_node())
    options.update(get_options_cto())
    options.update(get_options_net())
    return options 

def _optfmt(opt, arg):
    o = opt.rstrip(':=') # we rely on arg != None
    single = len(o)==1
    x = '%s%s' % ((single and 1 or 2) * '-', o)
    if arg and single:
        x += ' <%s>' % arg
    elif arg:
        x += '=<%s>' % arg
    return x

def _get_options_usage(options):
    if options is None:
        return [('', '', '')]
    keys = ['opts', 'help-desc', 'help-arg', 'remote']
    a = [[opt.get(k) for k in keys] for opt in options.itervalues()]
    b = filter(lambda x: x[1], a)
    c = [ (map(lambda o: _optfmt(o, x[2]), x[0]), x[1], x[3]) for x in b]
    d = [ (', '.join(x[0]), x[2] and '*' or '', x[1]) for x in c]
    def sortfunc(x):
        m = re.match('^(-*).*$', x[0])
        return (m and len(m.group(1)) or 0, x[0])
    d.sort(key=sortfunc)
    return d

def get_options_usage(header=None, options=None, extra=[]):
    if header is None:
        header = [
            "Usage: %s [OPTIONS]" % argslib.appname(),
            "",
            "OPTIONS (* = may be specified remotely):",
            ]
    if options is None:
        options = [
            get_options_remote(),
            get_options_non_remote(),
            None,
            get_options_node(),
            None,
            get_options_cto(),
            None,
            get_options_cmdb(),
            None,
            get_options_action(),
            None,
            # No net options displayed for isi_mfg_check
            ]
    options = map(_get_options_usage, options)
    options = reduce(lambda a,b:a+b, options)
    w = [max(map(len, zip(*options)[i])) for i in range(3)]
    options = ['  %-*s %-*s %s' % (w[0], o[0], w[1], o[1], o[2])
               for o in options]
    output = header + options + extra
    return '\n'.join(output)

### END: MOVED CONTENTS OF isi.hw.check.mfg.options here, for now
#########################################################################


mfg_options = get_options()

# These required options are automatically set on call to isi_mfg_check
# These required options are NOT displayed in --help output

required_mfg_options_keys = [
    'no_remote_logging',
    'no_remote_opts',
    'skip_identify',
    'chassisconfig',
    ]

# Track known VALID isi_mfg_check args.
# valid_mfg_options_dicts are grouped by functionality, options dicts
# valid_mfg_options_keys are additional discrete options, options dict keys

valid_mfg_options_dicts = [
    get_options_cto(),
    get_options_node(),
    get_options_cmdb(),
    get_options_net(),
    ]

valid_mfg_options_keys = [
    'newserial',
    ]

# Create options dictionaries for usage() and main()

required = {}
for opt in required_mfg_options_keys:
    required.update({opt: mfg_options[opt]})

valid = {}
for opt in valid_mfg_options_keys:
    valid.update({opt: mfg_options[opt]})
for opts in valid_mfg_options_dicts:
    valid.update(opts)

def usage(code):
    header = [
        'Usage: %s [OPTIONS]' % os.path.basename(sys.argv[0]),
        '',
        'All OPTIONS are passed through to the underlying tools.',
        'All OPTIONS are optional; Tool will prompt for inputs.',
        '',
        'OPTIONS include:',
        ]
    # Only display valid options; Do not display (internal) required options
    usage_options = valid_mfg_options_dicts
    for opt in valid_mfg_options_keys:
        usage_options.append({opt: mfg_options[opt]})
    orders = cto.VALID_ORDERS_STRINGS
    extras1 = [
        ('METHOD', cto.CMDB_ACCESS_VALID_METHODS_STRING2),
        ('USER', 'Suggested: node'),
        ('ORDER', orders[0]),
        ]
    extras1 += [('', order) for order in orders[1:]]
    extras2 = [
        (cto.CMDB_ACCESS_MOUNT,
         'Use NFS mount point (Suggested default)'),
        (cto.CMDB_ACCESS_SCP,
         'Use scp/ssh commands (Multiple password prompts)'),
        (cto.CMDB_ACCESS_LOCAL,
         'Use local file, no network'),
        ]
    width = max(map(len, zip(*(extras1+extras2))[0]))
    wstr = lambda (s1, s2): '  %-*s    %s' % (width, s1, s2)
    extra = [
        '',
        'Valid OPTIONS values include:',
        ]
    extra += map(wstr, extras1)
    extra += [
        '',
        'Valid METHOD values include:',
        ]
    extra += map(wstr, extras2)
    print >> sys.stderr, get_options_usage(header, usage_options, extra)
    sys.exit(code)

def main():

    # Create lists of option strings from option dicts
    required_options = [opt['opts'][0] for opt in required.itervalues()]
    valid_options = [opt['opts'][0] for opt in valid.itervalues()]
    all_options = required_options + valid_options + ['h','help']

    # Create short and long options for use with getopt
    is_short = lambda x: len(x.strip(':=')) == 1
    short_options = ''.join(filter(is_short, all_options))
    long_options = filter(lambda o: not is_short(o), all_options)

    try:
        opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
    except getopt.GetoptError, err:
        print str(err)
        usage(1)

    # Create '-o'/'--option' option strings for use with getopt results
    def option_string(s):
        s = s.strip(':=')
        if len(s) == 1:
            return '-%s' % s
        else:
            return '--%s' % s
    required_opts = map(option_string, required_options)
    valid_opts = map(option_string, valid_options)

    user_args = {}
    for opt, arg in opts:
        if opt == '-h':
            usage(0)
        elif opt in required_opts:
            pass
        elif opt in valid_opts:
            user_args[opt] = arg
        else:
            print 'Invalid option %s' % opt
            usage(1)

    user_options = reduce(
        lambda a, b: a + b,
        [[opt, arg] for (opt, arg) in user_args.iteritems()],
        [])

    # XXX PSI PIPELINE DEPRECATING Ok, so we can keep isi_update_cto:
    # XXX PSI PIPELINE DEPRECATING But it ain't going to do anything:
    # XXX PSI PIPELINE DEPRECATING This whole file is about setting up to run isi_mfg_check !!!
    cmd = '/usr/bin/isi_hwtools/isi_mfg_check'
    opts = [cmd] + required_opts + user_options
    os.execv(cmd, opts)

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