#!/usr/bin/python3

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

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

def do_bond_cleanup():
    # Get all clag interfaces
    clagCfg = {}
    clagReloadScript = "/lib/clagctl-utils/clagctlRestartConfig"
    if os.path.isfile(clagReloadScript) and os.access(clagReloadScript, os.X_OK):
        clagCfgStr = subprocess.check_output([clagReloadScript]).decode()
        clagCfg = json.loads(clagCfgStr)
    clagIntfs = clagCfg.get("clagIntfs", {})
    peerlinkIntfs = clagCfg.get("peerlinkIntfs", {})

    DEVNULL = open(os.devnull, 'wb')
    for clagIntf in clagIntfs:
        bondSysFs = "/sys/class/net/" + clagIntf + "/bonding"
        # if not bond do nothing
        if not os.path.isdir(bondSysFs):
            continue

        # protodown all the slaves
        bondMembers = []
        try:
            for line in open(bondSysFs + "/slaves"):
                bondMembers.extend(line.strip().split())
        except IOError:
            pass
        for bondMember in bondMembers:
            cmd = "/bin/ip link set %s protodown on protodown_reason clag on" % bondMember
            subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
            #print cmd

            # clear dormant mode on the bond
            cmd = "/bin/ip link set %s mode default" % clagIntf
            subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
            #print cmd
    for peerlinkIntf in peerlinkIntfs:
        try:
            if args.clagInit:
                cmd = "/sbin/bridge link set dev %s learning off" % peerlinkIntf
                subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
                # Flush the dynamic mac entries on the peerlink
                cmd = "/bin/ip link set dev %s type bridge_slave fdb_flush" % peerlinkIntf
                subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
                cmd = "/sbin/bridge link set dev %s peerlink on" % peerlinkIntf
                subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
            else:
                cmd = "/sbin/bridge link set dev %s peerlink off" % peerlinkIntf
                subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
                cmd = "/sbin/bridge link set dev %s learning on" % peerlinkIntf
                subprocess.call(cmd.split(), stdout=DEVNULL, stderr=DEVNULL)
        except:
            pass


parser = argparse.ArgumentParser(description="Get Clag Configs")
parser.add_argument("--clagInit", action='store_true',
                    help=argparse.SUPPRESS)
args = parser.parse_args()
do_bond_cleanup()
