#!/usr/bin/python

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

#
#   Import the necessary modules
#
try:
    import subprocess
    import os
    import json
except ImportError, 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])
        clagCfg = json.loads(clagCfgStr)
    clagIntfs = clagCfg.get("clagIntfs", {})

    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" % 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


do_bond_cleanup()
