#!/usr/bin/python

# Import the required modules
try:
    import subprocess
    import re
except ImportError, e:
    raise ImportError (str(e) + "- required module not found")
except KeyboardInterrupt:
    exit(-1)

# If user does ifup of just peerlink but vxlan devices have been configured
# and are up already, then go through all vxlan devices in the system and put
# them in proto-down state. Clagd will eventually bring them up after
# consistency check.

def clagProtoDownVxlanIfs():
    try:
        ifaceStr = subprocess.check_output(['/bin/ip', '-d', '-o', 'link', 'show'])
    except subprocess.CalledProcessError, e:
        print '%s: /bin/ip -d -o link show failed' % str(e)
        return

    if not ifaceStr:
        return

    for line in ifaceStr.splitlines():
        if line.find(" vxlan id ") > 0:
            field = re.split(r'[\s:]*\s', line)
            try:
                if line.find("protodown on") < 0:
                    subprocess.check_output(['/bin/ip', 'link', 'set', field[1], 'protodown', 'on'])
            except subprocess.CalledProcessError, e:
                print '%s: /bin/ip link set %s protodown on failed' %(str(e), field[1])

clagProtoDownVxlanIfs()
