#!/usr/bin/env python2
from __future__ import print_function

import argparse
import isi.hw.hal as hal
import isi.net.backendmon.frus as be_frus
import isi.net.backendmon.util as be_util
import json
import sys

def _be_switch_should_exist():
    '''Determines whether a backend Ethernet switch should exist.'''
    return (not hal.hasInfiniband()) and (not hal.isVirtualNode())

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

if __name__ == '__main__':
    if not _be_switch_should_exist():
        eprint('Dumping fabric not supported on this platform.')
        sys.exit(1)

    desc = 'Dump members of a given backend interface.'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('lni',
                        help='Backend interface used to dump fabric members.',
                        choices=['int-a', 'int-b'])
    args = parser.parse_args()
    lni = args.lni
    if be_util.lni_to_if(lni) is None:
        eprint('Invalid backend lni.')
        sys.exit(1)
    be_util.multicast_ping(lni)
    switch_addr, oui = be_util.intuit_switch_addr(lni)
    if switch_addr is None:
        eprint('Could not discover switch address.')
        sys.exit(1)
    be_util.unicast_ping(lni, switch_addr)
    # XXX This section sort of sucks. It relies on this script knowing that
    # certain switch types use SNMP versus REST, but since the original
    # switch monitoring wasn't designed to be that extensible, it is what
    # it is.
    try:
        if be_util.DELL_OUIS(oui) is False:
            session = be_frus.get_snmp_session(switch_addr)
            lldp_topo = be_frus.lldp_walk(session)
            switch_serial = be_frus.entity_serial_number(session, 1)
            switch_desc = be_frus.sys_desc(session)
        else:
            getter = be_frus.fru_getter(oui, switch_addr)
            lldp_topo = be_frus.os10_isilon_lldp(switch_addr)
            switch_serial = getter.serial_number
            switch_desc = be_frus.os10_sysdesc(switch_addr)
    except be_frus.FRUGetterTimeout:
        msg ='Query to switch at {switch_addr} timed out.'
        msg = msg.format(**locals())
        eprint(msg)
        sys.exit(1)

    label = '{switch_desc} ({switch_serial})'.format(**locals())
    out = {label: lldp_topo}
    print(json.dumps(out, indent=4))
