#!/usr/bin/python
#
# vim:expandtab ts=4
# in order to use the embedded vim commands "set modeline" is required in your .vimrc file

# -*- coding: utf-8 -*-

import subprocess
import sys
import os
import signal
from threading import Timer
import resource;

maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
    maxfd = 1024

for fd in range(3, maxfd):
    try:
        os.close(fd)
    except OSError as e:
        pass

if(len(sys.argv)<2):
    sys.exit("usage: %s <neighbor IP address>" % sys.argv[0])

neighbor=sys.argv[1]
os.setpgrp()
timer = Timer(interval=60, function=lambda: os.killpg(os.getpid(), signal.SIGKILL))
timer.start()
try:
    ret=subprocess.check_output(['/usr/bin/vtysh', '-c', 'show ip bgp neighbors'])
except subprocess.CalledProcessError as e:
    ret=None

timer.cancel()

foundNeighbor=False
neighborStatus='Idle'
if ret:
    for line in ret.split('\n'):
        if line.find('BGP neighbor is %s' % neighbor)>=0:
            foundNeighbor=True
        elif line.find('BGP neighbor is')>=0:
            foundNeighbor=False

        if foundNeighbor and line.find('BGP state')>=0:
            line=line.replace('BGP state', '')
            line=line.strip(' =')
            if line.find(' ')>0:
                line=line[0:line.find(' ')]
            neighborStatus=line
            neighborStatus=neighborStatus.strip(',')

if not foundNeighbor:
    sys.exit(0)

doclear = False
if neighborStatus in ('Idle', 'Connect'):
    doclear = True
else:
    timer = Timer(interval=60, function=lambda: os.killpg(os.getpid(), signal.SIGKILL))
    timer.start()
    try:
        ret = subprocess.check_output(['/usr/sbin/ip', 'route', 'show', 'table', 'all',
                                       'via', neighbor, 'proto', 'bgpext'])
        timer.cancel()
        if not ret:
            doclear = True
    except subprocess.CalledProcessError as e:
        sys.exit(0)

if doclear:
    timer = Timer(interval=60, function=lambda: os.killpg(os.getpid(), signal.SIGKILL))
    timer.start()
    subprocess.call(['/usr/bin/vtysh', '-c', 'clear ip bgp {}'.format(neighbor)])
    timer.cancel()
