#!/usr/bin/env python3

import os
import sys
import time

announce_flow_1 = 'announce flow route { match { source 0.0.0.0/32; destination 0.0.0.0/32; destination-port =3128; protocol tcp; } then { rate-limit 0; } }'
withdraw_flow_1 = (
    'withdraw flow route { match { source 0.0.0.0/32; destination 0.0.0.0/32; destination-port =3128; protocol tcp; } }'
)
announce_flow_2 = 'announce flow route { match { source 255.255.255.255/32; destination 255.255.255.255/32; } then { rate-limit 65535; } }'

time.sleep(0.2)  # let the EOR pass

messages = [
    withdraw_flow_1,
    announce_flow_1,
    announce_flow_2,
    announce_flow_1,  # nop
    announce_flow_2,  # nop
    withdraw_flow_1,
    announce_flow_1,
]

while messages:
    message = messages.pop(0)
    try:
        sys.stdout.write(message + '\n')
        sys.stdout.flush()
    except IOError:
        sys.stderr.write('IOError - ExaBGP exited ? ')
        sys.stderr.write('Could not write message: %s\n' % message)
        sys.stderr.flush()

try:
    now = time.time()
    while os.getppid() != 1 and time.time() < now + 1:
        line = sys.stdin.readline().strip()
        if not line or 'shutdown' in line:
            break
        time.sleep(0.5)
except IOError:
    pass
