#!/usr/bin/env python

"""
This utility performs a tree walk over the given PSI Tree Walk Mapping,
expected to be in PSI config space in "map.NAME" hierarchy.

If the tree walk definition includes a "map.NAME.psi" entry, then that
PSI key will be set with the resulting tree walk value, if any.

Other optional PSI keys can be set during the walk as well -- see 'psiset'.

The supported tree walk node types are flexible, supporting these types of nodes:
 o 'psi':
   Reads a given PSI key.
   Walks the given values lists performing comparison methods.
   At the first valid comparison match:
   EITHER a 'next' node id is visited, OR a 'result' is returned.
 o 'command':
   Executes the given command.
   Otherwise the same as 'psi', using command output instead of PSI Get result.
 o 'resume':
   Equivalent to a 'canned command' specific to Resume EEPROM gets using
   isi_fcb_vpd_tool, for the given Resume EEPROM (specified with devid).
   Expected values behavior: a Resume 'key' must be given, and if it is found,
   then the expected 'psi' key is set with this result.
   "Either-Or" behavior is optional, and if not given, the next value
   in the list will be visited.
 o 'terminal':
   Convenience node type for clearly defining an end to a Tree Walk decision
   path, identified with optional 'comment'.

Most node types support optional 'psiset' settings, specifying a PSI key
to be set on any valid 'matches'. If 'value' is given, this is used,
otherwise the 'command' output may be used.
"""

import argparse
import re
import sys

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

NODE_KEYS = {
    'psi': {
        'required': [('id', int), ('psi', str), ('type', str)],
        'eitheror': [],
        'optional': [('comment', str), ('psiset', str), ('psisettype', str)],
        'values': {
            'required': [('method', str), ('match', None)],
            'eitheror': [('next', int), ('result', int)],
            'optional': [('comment', str), ('value', None)],
        },
    },
    'command': {
        'required': [('id', int), ('command', str)],
        'eitheror': [],
        'optional': [('comment', str), ('psiset', str), ('psisettype', str)],
        'values': {
            'required': [('method', str), ('match', str)],
            'eitheror': [('next', int), ('result', int)],
            'optional': [('comment', str), ('value', None)],
        },
    },
    'resume': {
        'required': [('id', int), ('devid', int)],
        'eitheror': [],
        'optional': [('comment', str)],
        'values': {
            'required': [('method', str), ('key', str), ('psi', str), ('type', str)],
            'eitheror': [('next', int), ('result', int), (None, None)],
            'optional': [('comment', str)],
        },
    },
    'static': {
        'required': [('id', int)],
        'eitheror': [],
        'optional': [('comment', str)],
        'values': {
            'required': [('method', str), ('psi', str), ('type', str), ('value', None)],
            'eitheror': [('next', int), ('result', int), (None, None)],
            'optional': [('comment', str)],
        },
    },
    'terminal': {
        'required': [('id', int), ('result', int)],
        'eitheror': [],
        'optional': [('comment', str)],
        'values': None,
    }
}

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

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_node_ids():
    # We don't know how many nodes there are, so grow until stops growing
    # NB: These "id" values we're grabbing are not == list indices!
    def get_key(i):
        return 'map.%s.nodes.%d.id' % (args.map, i)
    result = []
    ni = 0
    nodes_inc = 10
    while nodes_inc:
        nodes = [psi.getInt(get_key(i)) for i in range(ni, ni + nodes_inc)]
        nodes = filter(lambda x: x is not None, nodes)
        ni += len(nodes)
        nodes_inc = len(nodes)
        result.extend(nodes)
    return result

def get_psi(node, key, typ, i, j=None):
    debug_func_call("get_psi(%s, %s, %s, %s)" % (key, typ, i, j))
    def get_key(i, j, key):
        if j is None:
            return 'map.%s.nodes.%d.%s' % (args.map, i, key)
        return 'map.%s.nodes.%d.values.%d.%s' % (args.map, i, j, key)
    if typ in [int, 'int']:
        val = psi.getInt(get_key(i, j, key))
    elif typ in ['uint64']:
        val = psi.getUint64(get_key(i, j, key))
    elif typ in [str, 'str', 'string']:
        val = psi.getString(get_key(i, j, key))
    elif typ in [bool, 'bool', 'boolean']:
        val = psi.getBool(get_key(i, j, key))
    elif typ == 'VALUES-LIST':
        val = get_values(node, i)
    elif typ is None:
        # What do we have that supports None ...
        if key == 'value':
            # If this node has optional psiset, great, attempt.
            # Otherwise, quietly abort. 'value' is an optional key.
            if 'psiset' in node:
                typ = node.get('psisettype', '???')
                val = get_psi(node, key, typ, i, j)
            else:
                val = None
        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(node, key, typ, val):
    nid = node and (node.get('id') and 'node id %s, ' % node.get('id')) or ''
    debug_func_call("set_psi(%s%s, %s, %s)" % (nid, 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 %skey '%s'" % (typ, nid, key))
        rc = -1
    if rc is None: # PSI API Error
        rc = -1
    if nid:
        wid, wkey, wtyp, wval = 2, 30, 3, 20
        verbose(3, "Id %*d: %-*s: (%*s) %-*s: [SET %sSUCCESSFULLY]" %
                (wid, node.get('id'), wkey, key, wtyp, typ, wval, val,
                 (rc != 0) and "UN" or ""))
    return rc

def lt(a, b):
    return a < b

def le(a, b):
    return a <= b

def eq(a, b):
    return a == b

def ge(a, b):
    return a >= b

def gt(a, b):
    return a > b

INT_COMPARE_METHOD = {
    lt: ('LT', '<', 'less', 'lessthan'),
    le: ('LE', '<=', '=<', 'lessthanequal', 'lessthanequals',
         'lessequal', 'lessequals'),
    eq: ('EQ', '==', 'equal', 'equals'),
    ge: ('GE', '>=', '=>', 'greaterthanequal', 'greaterthanequals',
         'greaterequal', 'greaterquals'),
    gt: ('GT', '>', 'greater', 'greaterthan'),
}

INT_COMPARE_METHODS = reduce(lambda a, b: a + b,
                             map(list, INT_COMPARE_METHOD.values()))

def get_psi_match_value(node, method, i, j):
    debug_func_call("get_psi_match_value(%s, %s, %s)" % (method, i, j))
    key = 'match'
    if method in ['default']:
        val = True
    elif method in ['regex']:
        val = get_psi(node, key, str, i, j)
    elif method in INT_COMPARE_METHODS:
        val = get_psi(node, key, int, i, j)
    elif method is None:
        raise Exception("No node %d value %d match method defined" %
                        (i, j))
    else:
        raise Exception("Invalid node %d value %d match method '%s' "
                        "(for get_psi_match_value function)" %
                        (i, j, method))
    return val

def get_value(node, i, j):
    debug_func_call("get_value(%s, %s)" % (i, j))
    value = {}
    nmethod = node.get('method')
    if not nmethod:
        raise Exception("No node %d method defined" % (i))
    if nmethod in ['terminal']:
        return None
    KEYS = NODE_KEYS.get(nmethod, {}).get('values', None)
    if not KEYS:
        raise Exception("Invalid node %d method '%s': No values defined" %
                        (i, nmethod))
    for key, typ in KEYS['required']:
        vmethod = value.get('method') # Will get set eventually; Required
        notreq = vmethod in ['default'] and nmethod in ['command', 'resume']
        if notreq:
            val = None
        elif key == 'match' and nmethod in ['psi']:
            val = get_psi_match_value(node, vmethod, i, j)
        elif key == 'value' and nmethod in ['static']:
            val = get_psi(node, key, value.get('type'), i, j)
        else:
            val = get_psi(node, key, typ, i, j)
        if val is None:
            if vmethod in ['default'] and nmethod in ['static']:
                notreq = True
            if notreq:
                pass
            else:
                raise Exception("Unable to get node %d value %d key '%s' "
                                "(required)" %
                                (i, j, key))
        else:
            value[key] = val
    eitheror_count = 0
    eitheror_none_allowed = False
    for key, typ in KEYS['eitheror']:
        if key is None and typ is None:
            # Special indicator that "None of either-or is acceptable",
            # as might be expected if we want to do an action (psiset?)
            # and continue through our values list...
            eitheror_none_allowed = True
            continue
        val = get_psi(node, key, typ, i, j)
        if val is None:
            pass # :shrug:
        else:
            eitheror_count += 1
            value[key] = val
    if eitheror_count == 0 and not eitheror_none_allowed:
        eitheror_keys = [k for (k,t) in KEYS['eitheror']]
        raise Exception("Unable to get at least one node %d value key: %s "
                        "(required)" %
                        (i, ', '.join(eitheror_keys)))
    for key, typ in KEYS['optional']:
        val = get_psi(node, key, typ, i, j)
        if val is None:
            pass # :shrug:
        else:
            value[key] = val
    return value

def get_values(node, i):
    # We don't know how many values there are, so grow until stops growing
    def get_key(i, nj):
        return 'map.%s.nodes.%d.values.%d.method' % (args.map, i, nj)
    values = []
    nj = 0
    while psi.getString(get_key(i, nj)) is not None:
        values.append(get_value(node, i, nj))
        nj += 1
    return values

def get_node(i):
    node = {}
    # All nodes require 'method' as well as 'id'.
    # NB: Debated allowing default 'psi' behavior, but figured safer
    # to enforce required explicit 'method' value in psi.conf files.
    nmethod = get_psi(node, 'method', str, i)
    debug_func_call("get_node(%d): method=%s" % (i, nmethod))
    KEYS = NODE_KEYS.get(nmethod, None)
    if not KEYS:
        raise Exception("Invalid node %d method '%s'" %
                        (i, nmethod))
    node['method'] = nmethod
    for key, typ in KEYS['required']:
        val = get_psi(node, 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(node, key, typ, i)
        if val is None:
            pass # :shrug:
        else:
            node[key] = val
    if KEYS['values']:
        val = get_psi(node, 'values', 'VALUES-LIST', i)
        if val is None:
            raise Exception("Unable to get node %d values" % (i))
        else:
            node['values'] = val
    return node

def get_nodes():
    # We don't know how many nodes there are, so grow until stops growing
    # NB: The "id" values we're grabbing are not == list indices!
    def get_key(i):
        return 'map.%s.nodes.%d.id' % (args.map, i)
    nodes = []
    ni = 0
    while psi.getInt(get_key(ni)) is not None:
        nodes.append(get_node(ni))
        ni += 1
    return nodes

def get_nodes_psi_set():
    # Optionally, mapping may define a psi key (and type) to set with result
    def get_key(key):
        return 'map.%s.%s' % (args.map, key)
    key = psi.getString(get_key('psi'))
    typ = psi.getString(get_key('type'))
    return key, typ

def set_psi_result(val):
    key, typ = get_nodes_psi_set()
    if not key:
        return 0
    if not typ:
        warn("No type specified for final PSI key '%s'; attempting string" %
             (key))
        typ = 'str'
    return set_psi(None, key, typ, val)

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

wid, wnmethod, wvmethod, wpsi, wmatch, wnext, wpsiset = 2, 8, 8, 66, 30, 12, 20

def display_value(node, (i, value)):
    indent = 2+2+3 # Ref display_node()
    nmethod = str(node.get('method'))
    nextresult = ("%s%s" % (
        'next'   in value and ('Next=%s' % value.get('next')) or '',
        'result' in value and ('Result=%s' % value.get('result')) or ''))
    comment = value.get('comment') and ("(%s)" % value.get('comment')) or ''
    psiset, psival = node.get('psiset'), value.get('value')
    if psiset and psival is not None:
        psisetval = '=> %s' % psival
    else:
        psisetval = ''
    if nmethod in ['psi']:
        vmethod, match = [value.get(k) for k in ('method', 'match')]
        print("%*s%0*d. %-*s %*s: %-*s:: %-*s %-*s %s" %
              (indent, "", wid, i, wnmethod, '', wvmethod, vmethod,
               wmatch, match, wnext, nextresult, wpsiset, psisetval, comment))
    elif nmethod in ['command']:
        # Effectively same as psi
        vmethod, match = [value.get(k) for k in ('method', 'match')]
        print("%*s%0*d. %-*s %*s: %-*s:: %-*s %-*s %s" %
              (indent, "", wid, i, wnmethod, '', wvmethod, vmethod,
               wmatch, match, wnext, nextresult, wpsiset, psisetval, comment))
    elif nmethod in ['resume']:
        devid = node['devid']
        key, psi, vmethod = [value.get(k) for k in ('key', 'psi', 'method')]
        if not nextresult:
            nextresult = 'Devid=0x%02x: %s' % (devid, key)
        print("%*s%0*d. %-*s %*s: %-*s:: %-*s %-*s %s" %
              (indent, "", wid, i, wnmethod, '', wvmethod, vmethod,
               wmatch, psi, wnext, nextresult, wpsiset, psisetval, comment))
    elif nmethod in ['static']:
        vmethod = value.get('method')
        psi, psitype, psivalue = [value.get(k) for k in ('psi', 'type', 'value')]
        if vmethod in ['default']:
            print("%*s%0*d. %-*s %*s: %-*s:: %-*s %-*s %s" %
                  (indent, "", wid, i, wnmethod, '', wvmethod, vmethod,
                   wmatch, "", wnext, nextresult, wpsiset, psivalue, comment))
        else:
            print("%*s%0*d. %-*s %*s: %-*s:: %-*s %-*s %s" %
                  (indent, "", wid, i, wnmethod, '', wvmethod, psitype,
                   wmatch, psi, wnext, nextresult, wpsiset, psivalue, comment))
    elif nmethod in ['terminal']:
        warn("Node method %s shouldn't have values" % nmethod)
        print("%*s%0*d. %-*s %*s" %
              (indent, "", wid, i, wnmethod, '', wvmethod, value))
    else:
        warn("Node method %s unknown" % nmethod)

def display_values(node, values):
    map(lambda v: display_value(node, v), enumerate(values))

def display_node((i, node)):
    values = node.get('values', [])
    id, typ, nmethod = [node.get(k) for k in ('id', 'type', 'method')]
    comment = node.get('comment') and ("(%s)" % node.get('comment')) or ''
    if nmethod in ['psi']:
        psi = node.get('psi')
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, nmethod,
               wvmethod+1, '(%s)' % typ, wpsi, psi, comment))
    elif nmethod in ['command']:
        command = node.get('command')
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, nmethod,
               wvmethod+1, '', wpsi, command, comment))
    elif nmethod in ['resume']:
        devid = node.get('devid')
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, nmethod,
               wvmethod+1, '', wpsi, '', comment))
    elif nmethod in ['static']:
        result = node.get('result')
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, nmethod,
               wvmethod+1, '', wpsi, '', comment))
    elif nmethod in ['terminal']:
        result = node.get('result')
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, nmethod,
               wvmethod+1, '', wpsi, result, comment))
    else:
        print("%0*d. Id=%0*d. %-*s %*s %-*s %s" %
              (wid, i, wid, id, wnmethod, "???",
               wvmethod+1, '', wpsi, '', comment))
    psiset, psisettype = [node.get(k) for k in ('psiset', 'psisettype')]
    if psiset:
        print("%*s     %*s  %-*s %*s %-*s %s" %
              (wid, '', wid, '', wnmethod, "psiset",
               wvmethod+1, '(%s)' % psisettype, wpsi, psiset, ''))
    display_values(node, values)

def display_nodes(nodes):
    print("Tree Walk Mapping for '%s': %d mapping nodes defined:" %
          (args.map, len(nodes)))
    map(display_node, enumerate(nodes))

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

def tree_node_result_psi(node):
    wid, wkey, wtyp, wval = 2, 30, 3, 20
    id, key, typ, com = [node.get(k) for k in ('id', 'psi', 'type', 'comment')]
    if typ in [int, 'int']:
        val = psi.getInt(key)
    elif typ in [str, 'str', 'string']:
        val = psi.getString(key)
    else:
        raise Exception("Unknown/Unsupported psi key type '%s' "
                        "for node id %s, key '%s'" %
                        (typ, id, key))
    verbose(2, "Id %*d: %-*s: (%*s) %-*s%s" %
            (wid, id, wkey, key, wtyp, typ, wval, val,
             com and ": %s" % com or ''))
    if val is None:
        raise Exception("Failed PSI Get for node id %s, key '%s'" %
                        (id, key))
    return val

def tree_node_check_psi(node, val):
    result = nextid = None
    id, key, typ = [node.get(k) for k in ('id', 'psi', 'type')]
    for value in node['values']:
        vmethod, match_val = [value.get(k) for k in ('method', 'match')]
        if vmethod in ['default']:
            if 'result' in value:
                result = value['result']
            elif 'next' in value:
                nextid = value['next']
            else:
                raise Exception("Missing 'next' or 'result' field "
                                "for node id %s, key '%s'" %
                                (id, key))
            break
        elif vmethod in ['regex']:
            if re.match(match_val, val):
                if 'result' in value:
                    result = value['result']
                elif 'next' in value:
                    nextid = value['next']
                else:
                    raise Exception("Missing 'next' or 'result' field "
                                    "for node id %s, key '%s'" %
                                    (id, key))
                break
        elif vmethod in INT_COMPARE_METHODS and typ in ['int']:
            cmp_func = None
            for cmp, cmp_keys in INT_COMPARE_METHOD.iteritems():
                if vmethod in cmp_keys:
                    cmp_func = cmp
                    break
            if not cmp_func:
                raise Exception("Unable to determine compare function "
                                "for node id %s, key '%s'" %
                                (id, key))
            if cmp_func(val, match_val):
                if 'result' in value:
                    result = value['result']
                elif 'next' in value:
                    nextid = value['next']
                else:
                    raise Exception("Missing 'next' or 'result' field "
                                    "for node id %s, key '%s'" %
                                    (id, key))
                break
        else:
            raise Exception("Invalid method '%s' "
                            "for node id %s, key '%s', type '%s'" %
                            (vmethod, id, key, typ))
    psiset = node.get('psiset')
    if psiset:
        # We expect value to be set. Warn to console if it's not,
        # and do nothing -- EXCEPT for method=default, which may
        # or may not have a value to be used with psiset.
        # NB: We could entertain the alternative ability to use
        # the "val" we previously got from PSI, but don't see a
        # use case now. Also make this explicit opt-in behavior.
        # (C.f. tree_node_check_command 'psiset' behavior.)
        psivalue = value.get('value')
        if psivalue is None:
            if vmethod in ['default']:
                pass
            else:
                note("Node id %s: Cannot set PSI key '%s' because "
                     "no value is specified." %
                     (id, psiset))
        else:
            psisettype = node.get('psisettype')
            if psisettype is None:
                # Let's complain but use string ...
                warn("Node id %s: Attempting to set PSI key '%s' "
                     "using type 'string' because not specified." %
                     (id, psiset))
                psisettype = 'str'
            rc = set_psi(node, psiset, psisettype, psivalue)
            if rc != 0:
                fail("Node id %s: Unable to set PSI key '%s' = '%s'" %
                     (id, psiset, psivalue))
    return (result, nextid)

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

def tree_node_result_command(node):
    # Command value entries are "supposed" to have required keys command
    # and match which work together: First exececute the command,
    # then compare output using (regex) match. IF there's a match,
    # then we use eitheror result or next, similar to 'psi' nodes.
    # If no match, we continue to next value list entry.
    # These value entries are also method=command which seems redundant,
    # but helps as we see below:
    # There is one special case value, for method=default, which does
    # NOT do a typical node command. Instead that just expects eitheror
    # result or next, similar to 'psi' nodes.
    wid, wcmd, wval = 2, 30, (3+3+20)
    id, cmd, com = [node.get(k) for k in ('id', 'command', 'comment')]
    rc, output = procs.get_cmd_output(cmd)
    if rc != 0:
        # raise Exception("")
        fail("Error %s running cmd: output = %s" % (rc, output))
        val = None
    else:
        # Hopefully just one line if done properly
        # Maybe we would want to take r = output[-1] ? (After checking for [])
        val = ','.join(output)
    verbose(2, "Id %*d: %-*s: %-*s%s" %
            (wid, id, wcmd, cmd, wval, val, com and ": %s" % com or ''))
    return val

def tree_node_check_command(node, val):
    result = nextid = None
    id, key, typ = [node.get(k) for k in ('id', 'psi', 'type')]
    match_val = None
    for value in node['values']:
        vmethod, match_val = value['method'], value.get('match')
        if vmethod in ['default']:
            if 'result' in value:
                result = value['result']
            elif 'next' in value:
                nextid = value['next']
            else:
                raise Exception("Missing 'next' or 'result' field "
                                "for node id %s, key '%s'" %
                                (id, key))
            break
        elif vmethod in ['regex']:
            m = re.match(match_val, val)
            if m:
                if 'result' in value:
                    result = value['result']
                elif 'next' in value:
                    nextid = value['next']
                else:
                    raise Exception("Missing 'next' or 'result' field "
                                    "for node id %s, key '%s'" %
                                    (id, key))
                break
        else:
            raise Exception("Invalid method '%s' "
                            "for node id %s, key '%s', type '%s'" %
                            (vmethod, id, key, typ))
    psiset = node.get('psiset')
    if psiset:
        # IFF 'value' is defined, then use that for psiset.
        # ELSE if 'match' is defined (see above!), then use the
        # command output (val) for psiset.
        # EXCEPT for method=default, which may or may not have
        # a value to be used with psiset (optional).
        psivalue = value.get('value')
        if psivalue is None:
            if vmethod in ['default']:
                pass
            elif match_val is not None:
                # Use command output
                psivalue = val
            else:
                note("Node id %s: Cannot set PSI key '%s' because "
                     "no value is specified." %
                     (id, psiset))
        if psivalue is not None:
            psisettype = node.get('psisettype')
            if psisettype is None:
                # Let's complain but use string ...
                warn("Node id %s: Attempting to set PSI key '%s' "
                     "using type 'string' because not specified." %
                     (id, psiset))
                psisettype = 'str'
            rc = set_psi(node, psiset, psisettype, psivalue)
            if rc != 0:
                fail("Node id %s: Unable to set PSI key '%s' = '%s'" %
                     (id, psiset, psivalue))
    return (result, nextid)

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

def tree_node_result_resume(node):
    wid, wdevid, wval = 2, 30, (3+3+20)
    id, devid, com = [node.get(k) for k in ('id', 'devid', 'comment')]
    vpd_tool = '/usr/bin/isi_hwtools/isi_fcb_vpd_tool'
    cmd = '%s -q --devid=%s dumpresume' % (vpd_tool, devid)
    rc, output = procs.get_cmd_output(cmd)
    if rc != 0:
        # raise Exception("")
        fail("Error %s running cmd: output = %s" % (rc, output))
        # Fallthrough below
    d = dict(filter(lambda r: len(r)==2,
                    [[x.strip() for x in o.split(':', 1)] for o in output]))
    verbose(2, "Id %*d: %-*s: %-*s%s" %
            (wid, id, wdevid, "Resume Devid %s" % devid,
             wval, "(%d keys)" % len(d), com and ": %s" % com or ''))
    return d

def tree_node_check_resume(node, val):
    result = nextid = None
    id, devid = [node.get(k) for k in ('id', 'devid')]
    if not isinstance(val, dict):
        raise Exception("Node id %s does not have a valid resume (devid %s) "
                        "data dict as expected" %
                        (id, devid))
    for value in node['values']:
        vmethod = value.get('method')
        reskey, psikey, psityp = [value.get(k) for k in ('key', 'psi', 'type')]
        if vmethod in ['default']:
            # 'resume' eitheror is next, result, or None, but it
            # makes sense that 'default' needs proper eitheror behavior
            if 'result' in value:
                result = value['result']
            elif 'next' in value:
                nextid = value['next']
            else:
                raise Exception("Missing 'next' or 'result' field "
                                "for node id %s, devid %s (method default)" %
                                (id, devid))
            break
        elif vmethod in ['resume']:
            missing = filter(None, [
                reskey is None and 'key' or None,
                psikey is None and 'psi' or None,
                psityp is None and 'typ' or None,
                ])
            if missing:
                raise Exception("Missing required resume info for node id %s, "
                                "devid %s: %s" %
                                (id, devid, ", ".join(missing)))
            psival = val.get(reskey)
            if psival is None:
                warn("Missing Resume Devid %s key %s; Unable to set PSI key %s" %
                     (devid, reskey, psikey))
            else:
                rc = set_psi(node, psikey, psityp, psival)
                if rc != 0:
                    fail("Node id %s: Unable to set PSI key '%s' = '%s'" %
                         (id, psikey, psival))
            # For 'resume' eitheror is optional...
            if 'result' in value:
                result = value['result']
                break # Note early break since optional
            elif 'next' in value:
                nextid = value['next']
                break # Note early break since optional
            else:
                pass # Optional -- else continue to next value in list
        else:
            raise Exception("Invalid method '%s' "
                            "for node id %s, key '%s', type '%s'" %
                            (vmethod, id, reskey, psityp))
    psiset = node.get('psiset')
    if psiset:
        # We expect value to be set. Warn to console if it's not,
        # and do nothing -- EXCEPT for method=default, which may
        # or may not have a value to be used with psiset.
        # If it's not set (and not default), use command output.
        psivalue = value.get('value')
        if psivalue is None:
            if vmethod in ['default']:
                pass
            else:
                note("Node id %s: Using command output to set PSI key '%s' "
                     "because no value is specified." %
                     (id, psiset))
                psivalue = val
        if psivalue is not None:
            psisettype = node.get('psisettype')
            if psisettype is None:
                # Let's complain but use string ...
                warn("Node id %s: Attempting to set PSI key '%s' "
                     "using type 'string' because not specified." %
                     (id, psiset))
                psisettype = 'str'
            rc = set_psi(node, psiset, psisettype, psivalue)
            if rc != 0:
                fail("Node id %s: Unable to set PSI key '%s' = '%s'" %
                     (id, psiset, psivalue))
    return (result, nextid)

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

def tree_node_result_static(node):
    wid, wresult, wval = 2, 30, (3+3+20)
    id, com = [node.get(k) for k in ('id', 'comment')]
    verbose(2, "Id %*d: %-*s: %-*s%s" %
            (wid, id, wresult, '', wval, '',
             com and ": %s" % com or ''))
    return None

def tree_node_check_static(node, val):
    result, nextid = None, None
    for value in node['values']:
        vmethod = value.get('method')
        psiset, psisettype, psivalue = [value.get(k) for k in ('psi', 'type', 'value')]
        if vmethod in ['default']:
            # 'static' eitheror is next, result, or None, but it
            # makes sense that 'default' needs proper eitheror behavior
            if 'result' in value:
                result = value['result']
            elif 'next' in value:
                nextid = value['next']
            else:
                raise Exception("Missing 'next' or 'result' field "
                                "for node id %s (method default)" %
                                (id))
            break
        elif vmethod in ['static']:
            if psisettype is None:
                # Let's complain but use string ...
                warn("Node id %s: Attempting to set PSI key '%s' "
                     "using type 'string' because not specified." %
                     (id, psiset))
                psisettype = 'str'
            rc = set_psi(node, psiset, psisettype, psivalue)
            if rc != 0:
                fail("Node id %s: Unable to set PSI key '%s' = '%s'" %
                     (id, psiset, psivalue))
        else:
            raise Exception("Invalid method '%s' for node id %s" %
                            (vmethod, id))
    return (result, nextid)

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

def tree_node_result_terminal(node):
    wid, wresult, wval = 2, 30, (3+3+20)
    id, result, com = [node.get(k) for k in ('id', 'result', 'comment')]
    val = int(result) # TODO Add protection?
    verbose(2, "Id %*d: %-*s: %-*s%s" %
            (wid, id, wresult, result, wval, val,
             com and ": %s" % com or ''))
    return val

def tree_node_check_terminal(node, val):
    result, nextid = val, None
    return (result, nextid)

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

TREE_NODE_RESULTS = {
    'psi':      tree_node_result_psi,
    'command':  tree_node_result_command,
    'resume':   tree_node_result_resume,
    'static':   tree_node_result_static,
    'terminal': tree_node_result_terminal,
}

TREE_NODE_CHECKS = {
    'psi':      tree_node_check_psi,
    'command':  tree_node_check_command,
    'resume':   tree_node_check_resume,
    'static':   tree_node_check_static,
    'terminal': tree_node_check_terminal,
}

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

def tree_walk(nodes):
    # ASSUME that "id" values are irrelevant, as long as they are unique.
    # DO NOT ASSUME that we need to start any any given id!
    # Instead, ASSUME that we ALWAYS start at the first [0] entry...
    if not len(nodes):
        raise Exception("No valid nodes defined!")
    # We do need unique ids, though, for this to work
    ids = list(set([n.get('id') for n in nodes]))
    debug_func_call("tree_walk(): ids #1 = %s" % ids)
    if len(nodes) != len(ids):
        raise Exception("Not all node ids are unique: %d nodes, "
                        "but %d unique ids" %
                        (len(nodes), len(ids)))
    ids = filter(lambda x: isinstance(x, int), ids)
    debug_func_call("tree_walk(): ids #2 = %s" % ids)
    if len(nodes) != len(ids):
        raise Exception("Not all node ids are integer valued")
    node = nodes[0]
    # One final sanity check: if any nodes ever get back to our starting id,
    # then we'll get into an infinite loop... Just check during our walk.
    # Later we can fix this to be a list and handle any possible loops.
    id = firstid = node.get('id')
    ndict = dict([(n.get('id'), n) for n in nodes])
    result, first = None, True
    while result is None:
        node = ndict[id]
        nmethod = node.get('method')
        func = TREE_NODE_RESULTS.get(nmethod)
        if not func:
            raise Exception("Invalid node method '%s'" % nmethod)
        val = func(node)
        func = TREE_NODE_CHECKS.get(nmethod)
        if not func:
            raise Exception("Invalid node method '%s'" % nmethod)
        result, nextid = func(node, val)
        debug_func_call(
            "tree_walk(id=%s): method=%s, val=%s, result=%s, nextid=%s" %
            (id, nmethod, val, result, nextid))
        id = nextid
        if not first and id == firstid:
            raise Exception("Invalid mapping: Detected infinite loop "
                            "to first Id = %s" %
                            (firstid))
        first = False
    return result

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

parser = argparse.ArgumentParser(
    description='Generate and set a value using PSI tree walk mapping info.')
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', required=True,
                    help='Specify PSI key mapping to use')
parser.add_argument('--dump', action='store_true',
                    help='Dump tree walk mapping to display and exit')

def main():
    global args
    args = parser.parse_args()
    try:
        nodes = get_nodes()
        debug(1, nodes)
        if args.dump:
            display_nodes(nodes)
            return 0
        result = tree_walk(nodes)
        if args.verbose: # Level 1 or higher
            print "result = %s" % result
        # Optionally save psi result
        set_psi_result(result)
        return 0
    except Exception as e:
        if args.debug:
            raise
        sys.stderr.write("Exception raised: %s\n" % e)
        return 1

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