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

import argparse
import binascii
import logging
import os
import platform
import shlex
import stat
import subprocess
import sys
import traceback

from collections import defaultdict

import isi.net.flexnet as flx
import isi.net.backendmon.util as util
import isi.config.array as array
import isi.config.ifs as ifs
import isi.hw.hal as hal

_LOGGER = logging.getLogger(__name__)

# Super gross, but this is how we get access to boxend.
sys.path.append('/usr/local/bin/')
try:
    from boxend import createUpdate
    from boxend import sendUpdate
    _BOXEN = True
except ImportError:
    _BOXEN = False

_ISILON_OUI = '00,15,1B'
_DELL_OUI = 'F8,B1,56'

_SYS_INTERFACE = 'configure system interface pattern {self.interface}\n'
_SYS_HOSTNAME = 'configure system hostname {self.hostname}\n'
_SYS_DESC = 'configure system description "{self.sys_desc}"\n'
_SYS_MGMT_IP = 'configure system ip management pattern {self.mgmt_ip}\n'
_CUSTOM_TLV_FMT = ('configure lldp custom-tlv replace oui {oui} '
                   'subtype {{subtype}} oui-info {{{{oui_info}}}}\n'
                   )
_CUSTOM_TLV_FMT_ISI = _CUSTOM_TLV_FMT.format(oui=_ISILON_OUI)
_CUSTOM_TLV_FMT_DELL = _CUSTOM_TLV_FMT.format(oui=_DELL_OUI)
_CUSTOM_TLV_MARKETING_NAME = _CUSTOM_TLV_FMT_ISI.format(subtype=1)
_CUSTOM_TLV_BOXEN_LABEL = _CUSTOM_TLV_FMT_ISI.format(subtype=2)
_CUSTOM_TLV_FAILOVER_IP = _CUSTOM_TLV_FMT_ISI.format(subtype=3)
_CUSTOM_TLV_LNI = _CUSTOM_TLV_FMT_ISI.format(subtype=4)
_CUSTOM_TLV_ROLE = _CUSTOM_TLV_FMT_DELL.format(subtype=1)
_CUSTOM_TLV_PREFIX = _CUSTOM_TLV_FMT_DELL.format(subtype=2)
_CUSTOM_TLV_FABRIC = _CUSTOM_TLV_FMT_DELL.format(subtype=3)

_CONF_PATH = '/etc/ifs/isi_lldpd_{lni_name}'
_PID_PATH = '/var/run/lldpd_{lni_name}.pid'
_LLDPCLI_LAUNCH_PATH = '/tmp/lldpcli_{lni_name}_launch.sh'
_LLDPD_CMD = ('/usr/local/sbin/lldpd -u /var/run/lldpd_{lni_name} '
              '-p {pid_path} '
              '-L ' + _LLDPCLI_LAUNCH_PATH)
_LLDPCLI_LAUNCH = '''#!/usr/bin/env sh
/usr/local/sbin/lldpcli -u /var/run/lldpd_{lni_name} -c {conf_file_path}
'''

_DEVNULL = open(os.devnull, 'wb')

class LLDPDConfig(object):
    '''Convenience class for generating the lldpd(8) configuration file.'''

    @staticmethod
    def str_to_hex_list_str(s):
        return ','.join((binascii.hexlify(c) for c in s))

    def __init__(self, interface=None, hostname=None, sys_desc=None,
                 mgmt_ip=None, failover_ip=None, lni=None,
                 marketing_name=None,
                 boxen_label=None, update=False):
        self.interface = interface
        self.hostname = hostname
        self.sys_desc = sys_desc
        self.mgmt_ip = mgmt_ip
        self.failover_ip = failover_ip
        self.lni = lni
        self.marketing_name = marketing_name
        self.boxen_label = boxen_label
        self.update = update

    def __str__(self):
        oui = _ISILON_OUI
        out = ''
        if not self.interface:
            raise Exception()
        out += _SYS_INTERFACE.format(**locals())
        if self.hostname:
            out += _SYS_HOSTNAME.format(**locals())
        if self.sys_desc:
            if len(self.sys_desc) > 255:
                raise Exception()
            out += _SYS_DESC.format(**locals())
        if self.mgmt_ip:
            out += _SYS_MGMT_IP.format(**locals())
        ids = {'int-a': '1', 'int-b': '2'}
        oui_info = self.__class__.str_to_hex_list_str('isilon')
        out += _CUSTOM_TLV_ROLE.format(**locals())
        prefix = str(util.BACKEND_PREFIXES[self.lni].ip)
        oui_info = self.__class__.str_to_hex_list_str(prefix)
        out += _CUSTOM_TLV_PREFIX.format(**locals())
        oui_info = self.__class__.str_to_hex_list_str(ids[self.lni])
        out += _CUSTOM_TLV_FABRIC.format(**locals())
        if self.marketing_name:
            oui_info = self.__class__.str_to_hex_list_str(self.marketing_name)
            out += _CUSTOM_TLV_MARKETING_NAME.format(**locals())
        if self.boxen_label:
            oui_info = self.__class__.str_to_hex_list_str(self.boxen_label)
            out += _CUSTOM_TLV_BOXEN_LABEL.format(**locals())
        if self.failover_ip:
            oui_info = self.__class__.str_to_hex_list_str(self.failover_ip)
            out += _CUSTOM_TLV_FAILOVER_IP.format(**locals())
        if self.lni:
            oui_info = self.__class__.str_to_hex_list_str(self.lni)
            out += _CUSTOM_TLV_LNI.format(**locals())
        if self.update is True:
            # Make lldpd(8) update its information and send new LLDP PDU
            out += 'update\n'
        # Done configuring, configuration needs to end with resume.
        out += 'resume\n'
        return out

def log_exc(exc_type, value, tb):
    _LOGGER.error('Encountered uncaught exception:\n{e}\n{v}\n{tb}'
              .format(e=exc_type, v=value,
                      tb='\n'.join(traceback.format_tb(tb))))

# This scripts is a launcher/configuration generator for lldpd(8). Given a
# backend lni (int-a or int-b) it will generate an lldpd configuration,
# lldpcli launcher script, and start lldpd in the background.
def main(args):
    global _BOXEN
    lni_name = args.lni
    if args.no_boxen:
        _BOXEN = False
    if _BOXEN:
        boxen_update = createUpdate(label=None, chas=0, cache=True)
        response = sendUpdate(boxen_update)
        boxen_label = response['label']
    else:
        boxen_label = None
    lni_to_field = {'int-a': '_internal_a', 'int-b': '_internal_b'}
    backend_lnis = {l.name : l for l in flx.lni_query(ifs.DEVID_LOCAL,
                                                      flx.LNI_ANY_IDX,
                                                      flx.IFFLAG_INTERNAL)}
    if lni_name not in backend_lnis:
        _LOGGER.info('Invalid lni: {lni_name}'.format(**locals()))
        sys.exit(1)
    try:
        node = array.getLocalNode().__dict__
    except Exception:
        node = defaultdict(lambda: 'Unknown')
    inter = backend_lnis[lni_name].nic.name
    ip = node[lni_to_field[lni_name]]
    marketing_name = hal.getChassisMarketingName(0).replace(' ', '-')

    conf_file_path = _CONF_PATH.format(**locals())
    with open(conf_file_path, 'w') as conf_file:
        # We have to truncate the uname so it is < 255 characters.
        c = LLDPDConfig(inter, platform.node(),
                        platform.uname()[3].split(':')[0],
                        mgmt_ip=ip,
                        failover_ip=node['_failover'],
                        lni=lni_name,
                        marketing_name=marketing_name,
                        boxen_label=boxen_label,
                        update=args.update)
        conf_file.write(str(c))
        launch_path = _LLDPCLI_LAUNCH_PATH.format(**locals())
        with open(launch_path, 'w') as lldp_cli_file:
            lldp_cli_file.write(_LLDPCLI_LAUNCH.format(**locals()))
        st = os.stat(launch_path)
        os.chmod(launch_path, st.st_mode | stat.S_IEXEC)
        pid_path = _PID_PATH.format(**locals())

        # If requested for update, make lldpd(8) update its information
        # and send new LLDP PDU. Else, start lldpd in the background.
        if args.update:
            conf_file.close()
            subprocess.call(launch_path, shell=True,
                            stdout=_DEVNULL, stderr=_DEVNULL, close_fds=True)
        else:
            subprocess.call(shlex.split(_LLDPD_CMD.format(**locals())),
                            stdout=_DEVNULL, stderr=_DEVNULL, close_fds=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('lni')
    parser.add_argument('--no-boxen', action='store_true')
    parser.add_argument('--update', action='store_true')
    args = parser.parse_args()
    _LOGGER.setLevel(logging.DEBUG)
    fname = '/var/log/isi_lldpd-{args.lni}.log'.format(**locals())
    handler = logging.FileHandler(fname)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s',
                                           '%Y-%m-%d %H:%M:%S'))
    _LOGGER.addHandler(handler)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(message)s'))
    handler.setLevel(logging.DEBUG)
    _LOGGER.addHandler(handler)
    sys.excepthook = log_exc
    _LOGGER.info('Attempting to configure and run lldpd on %s.', args.lni)
    main(args)
