#!/usr/bin/python3 -u

# -------------------------------------------------------------------------------
#
# Copyright 2014, 2020 Cumulus Networks, inc  all rights reserved
#
# -------------------------------------------------------------------------------

#
#   Import the necessary modules
#
try:
    import argparse
    import subprocess
    import re
    import json
    import logging
    import logging.handlers
except ImportError as e:
    raise ImportError(str(e) + "- required module not found")
except KeyboardInterrupt:
    exit(-1)

# Note: Currently we only use the clag-id info from the rendered
# ifquery output.

def get_output(cmd):
    try:
        output = subprocess.check_output(cmd.split(' ')).strip()
        output = json.loads(output)
        return output
    except json.JSONDecodeError as je:
        logger.warning("Invalid format for the json data") 
    except Exception as e:
        logger.warning("failed to fetch the output")
    return None

def getAllPeerlinkInterfaces(peerlinkIntfPat):
    peerlinkIntfs = []
    bridge_show_cmd = "bridge -j link show"
    bridgeLinks = get_output(bridge_show_cmd)
    if bridgeLinks:
        for entry in bridgeLinks:
            if peerlinkIntfPat in entry.get("ifname", None):
                peerlinkIntfs.append(entry.get("ifname"))
    return peerlinkIntfs

def clagGetConfig(logger):
    clagCfg = {}
    clagIdCfg = {}
    try:
        ifaceout = subprocess.check_output(['/sbin/ifquery', '-a']).decode()
        logger.debug("/sbin/ifquery -a returned:")
        for line in ifaceout.splitlines():
            logger.debug("    " + line)
    except subprocess.CalledProcessError as e:
        return clagCfg

    ifPat = re.compile(r'^[ \t]*iface (?P<ifn>\S+)')
    clagIdPat = re.compile(r'^[ \t]*clag-id (?P<cid>\d+)')
    peerlinkPat = re.compile(r'^[ \t]*clagd-peer-ip \S+')
    ifName = None
    for line in ifaceout.splitlines():
        obj = ifPat.search(line)
        if obj:
            ifName = obj.group('ifn')
        obj = clagIdPat.search(line)
        if obj:
            clagId = obj.group('cid')
            if ifName:
                clagIdInfo = {}
                clagIdInfo['clagId'] = int(clagId)
                clagIdCfg[ifName] = clagIdInfo
            ifName = None
        obj = peerlinkPat.search(line)
        if obj:
            if ifName:
                clagCfg['peerlink'] = ifName
            ifName = None

    clagCfg['clagIntfs'] = clagIdCfg
    return clagCfg

parser = argparse.ArgumentParser(description="Get Clag Configs")
parser.add_argument("--debug", "-d", action='store_true',
                    help="Enable debugging output")
parser.add_argument("--clagBondDump", "-c", action='store_true', 
                   help="Dump only clagBonds")
args = parser.parse_args()
logger = logging.getLogger("clagctlRestartConfig")
if args.debug:
    logger.setLevel(logging.DEBUG)
logger.addHandler(logging.handlers.SysLogHandler(address='/dev/log'))

clagCfg = {}
CfgDict = clagGetConfig(logger)

clagCfg['clagIntfs'] = CfgDict.get('clagIntfs', {})

peerlinkIntf = CfgDict.get('peerlink', '')
peerlinkParent = peerlinkIntf.split('.')
peerlinkIntfs = []
if peerlinkParent:
    peerlinkIntfs = getAllPeerlinkInterfaces(peerlinkParent[0])
clagCfg['peerlinkIntfs'] = peerlinkIntfs

if args.clagBondDump:
    clagBondList = clagCfg.get("clagIntfs", {})
    print(" ".join(clagBondList))
else:
    print((json.dumps(clagCfg)))
