#!/usr/bin/python

# isi_psi_probe should be called by isi_psi_d after every
# initialization (or re-parsing) of PSI config files.
# This script is responsible for setting defined dynamic
# PSI variables -- using defined list of (PSI Key, Command)
# tuples in psi.conf files maintained just for this purpose.
# These files should place all tuples into a PSI namespace
# "psi.probe.(NAME).(LIST)" (c.f. psi.supported)
# At minimum, we expect psi.probe.primary.(LIST).
# Others may exist -- Since PSI APIs don't allow us to discover
# usysctl hierarchies easily, the only namespaces that are
# parsed automatically are those defined in the default list.

import argparse
import re
import sys

import isi.hw.psi as psi
import isi.app.lib.procs as procs

DEFAULT_PROBE_CONF_MAPS = [
    'primary'
]

NODE_KEYS = {
    'required': [('command', str), ('method', str)],
    'optional': [('comment', str), ('psi', str), ('type', str),
                 ('match', str), ('value', None)],
}

NODE_DUMP_KEYS = [
    # Ordered. Used for dumping node key-value info on warnings.
    'method', 'comment', 'command', 'psi', 'type', 'match', 'value'
]

# #############################################################################

def verbose(level, msg):
    if args.verbose >= level:
        print("%s" % msg)

def debug(level, msg):
    if args.debug >= level:
        print("%s" % msg)

def debug_func_call(msg):
    debug(5, "%s" % msg)

def note(msg):
    verbose(1, "NOTE: %s" % msg)

def warn(msg):
    print("WARNING: %s" % msg)

def fail(msg):
    print("FAILURE: %s" % msg)

# #############################################################################

def get_psi_map_key(mapping, index, key):
    return 'psi.probe.%s.%d.%s' % (mapping, index, key)

def get_psi(mapping, key, typ, i):
    val = None
    debug_func_call("get_psi(%s, %s, %s, %s)" % (mapping, key, typ, i))
    if typ in [int, 'int']:
        val = psi.getInt(get_psi_map_key(mapping, i, key))
    elif typ in ['uint64']:
        val = psi.getInt64(get_psi_map_key(mapping, i, key))
    elif typ in [str, 'str', 'string']:
        val = psi.getString(get_psi_map_key(mapping, i, key))
    elif typ is None:
        # What do we have that supports None ... Nothing! ??
        if key == 'value':
            # XXX Actually make this optional for now.
            pass
        else:
            raise Exception("Invalid psi key type None for node %s key '%s'" %
                            (i, key))
    else:
        raise Exception("Unknown psi key type '%s' for node %s key '%s'" %
                        (typ, i, key))
    return val

def set_psi(key, typ, val):
    debug_func_call("set_psi(%s, %s, %s)" % (key, typ, val))
    if typ in [str, 'str', 'string']:
        rc = psi.setString(key, str(val))
    elif typ in [bool, 'bool']:
        rc = psi.setBool(key, int(val))
    elif typ in [int, 'int']:
        rc = psi.setInt(key, int(val))
    elif typ in ['int32']:
        rc = psi.setInt32(key, int(val))
    elif typ in ['int64']:
        rc = psi.setInt64(key, int(val))
    elif typ in ['uint']:
        rc = psi.setUint(key, int(val))
    elif typ in ['uint32']:
        rc = psi.setUint32(key, int(val))
    elif typ in ['uint64']:
        rc = psi.setUint64(key, int(val))
    elif typ in ['double']:
        rc = psi.setDouble(key, float(val))
    else:
        warn("Unknown PSI type '%s' for key '%s'" % (typ, key))
        rc = -1
    if rc is None: # PSI API Error
        rc = -1
    wkey, wtyp, wval = 30, 3, 20
    verbose(3, "%-*s: (%*s) %-*s: [SET %sSUCCESSFULLY]" %
            (wkey, key, wtyp, typ, wval, val,
             (rc != 0) and "UN" or ""))
    return rc

# #############################################################################

def get_node(mapping, i):
    node = {}
    # All nodes require a 'method'.
    method = get_psi(mapping, 'method', str, i)
    debug_func_call("get_node(%s, %d): method=%s" % (mapping, i, method))
    KEYS = NODE_KEYS
    if not KEYS:
        raise Exception("Invalid node %d method '%s'" %
                        (i, method))
    node['method'] = method
    for key, typ in KEYS['required']:
        val = get_psi(mapping, key, typ, i)
        if val is None:
            raise Exception("Unable to get node %d key %s (required)" %
                            (i, key))
        else:
            node[key] = val
    for key, typ in KEYS['optional']:
        val = get_psi(mapping, key, typ, i)
        if val is None:
            pass # :shrug:
        else:
            node[key] = val
    return node

def get_nodes(mapping):
    # We don't know how many nodes there are, so grow until stops growing
    # NB: All entries require a 'method'
    def get_method(ni):
        return psi.getString(get_psi_map_key(mapping, ni, 'method'))
    nodes = []
    ni = 0
    while get_method(ni) is not None:
        nodes.append(get_node(mapping, ni))
        ni += 1
    return nodes

# #############################################################################

# Probe functions return -1 if skipped for any reason, else get_cmd_output rc

def probe_command(mapping, node, psikey=None):
    cmd = node.get('command')
    if not cmd:
        warn("Mapping '%s': No command specified, skipping" % mapping)
        return -1
    rc, output = procs.get_cmd_output(cmd, include_stderr=True)
    if rc:
        if isinstance(rc, int) and rc > 0x100:
            err = '%d (>>8 = %d)' % (rc, rc >> 8)
        else:
            err = '%s' % rc
        warn("Mapping '%s': Command '%s' return error code = %s" % (mapping, cmd, err))
    if args.verbose:
        if not output:
            print("Mapping '%s': Result of running %s: (No output)" % (mapping, cmd))
        else:
            w = 70
            print("Mapping '%s': Result of running %s:" % (mapping, cmd))
            print("-" * w)
            for o in output:
                print("%s" % o)
            print("-" * w)
    if psikey is None:
        if 'psi' in node:
            warn("Mapping '%s': Unexpected PSI '%s' specified with method '%s'; "
                 "Ignored, but this is likely undesired behavior?" %
                 (mapping, node.get('psi'), node.get('method')))
    else:
        key = node.get('psi')
        if not key:
            warn("Mapping '%s': Missing PSI key, required with method '%s'; "
                 "Skipping but this is likely undesired behavior?" %
                 (mapping, node.get('method')))
            return -1
        typ = node.get('type', 'str') # Default if missing is string?
        # Go with combined output, or last line, or ??? Or flexible w/param?
        if not output:
            warn("Mapping '%s': PSI key '%s': No output from command? "
                 "Skipping but this is likely undesired behavior?" %
                 (mapping, key))
        val = str(output[-1]).strip()
        note("Mapping '%s': Setting PSI '%s' with result '%s'" % (mapping, key, val))
        psirc = set_psi(key, typ, val)
        rc = (psirc != 0) and 1 or 0
    return rc

def probe_node(mapping, node):
    debug(1, "Mapping '%s': Probe node = %s" % (mapping, node))
    method = node.get('method')
    if method in ['execute']:
        result = probe_command(mapping, node)
    elif method in ['psi']:
        result = probe_command(mapping, node, psikey=True)
    else:
        result = -1
        warn("Mapping '%s': Unknown PSI Probe Method '%s', skipping" %
             (mapping, method))
    if result == -1:
        # SKIPPED, dump node key-value info
        wkey = max(map(len, NODE_DUMP_KEYS))
        for key in NODE_DUMP_KEYS:
            val = str(node.get(key, '[NOT SET]'))
            warn("Mapping '%s': %-*s = %s" %
                 (mapping.capitalize(), wkey, key, val))
    return result

def probe(mapping, nodes):
    results = [probe_node(mapping, node) for node in nodes]
    # return reduce(lambda a, b: a or b, results, 0)
    # Actually don't use final isi_psi_probe result code from these
    # individual probe commands; just display all results in verbose
    # mode, and don't consider any to be a failure for isi_psi_probe.
    return results

# #############################################################################

parser = argparse.ArgumentParser(
    description=(('Probe and set PSI values using PSI probe config info. '
                  'Default mappings: %s' %
                  ', '.join(DEFAULT_PROBE_CONF_MAPS))))
parser.add_argument('-d', '--debug', action='count',
                    help='Enable (increase) debug output')
parser.add_argument('-v', '--verbose', action='count',
                    help='Enable (increase) verbose output')
parser.add_argument('-m', '--map', action='append',
                    help='Specify PSI key mapping to use [Optional]')

def main():
    global args
    args = parser.parse_args()
    if args.map:
        mappings = args.map
    else:
        mappings = DEFAULT_PROBE_CONF_MAPS
    try:
        for mapping in mappings:
            nodes = get_nodes(mapping)
            debug(4, "Mapping '%s' nodes: %s" % (mapping, nodes))
            mresult = probe(mapping, nodes)
            verbose(1, "Mapping '%s' results: %s" % (mapping, mresult))
        return 0
    except Exception as e:
        if args.debug:
            raise
        sys.stderr.write("%s\n" % e)
        return 1

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