#!/usr/bin/python
import nemu, os, signal, subprocess
SCREEN = 'screen'

def disable_signal_on_children(sig):
    pid = os.getpid()
    sigint = signal.signal(sig, lambda *x: os.getpid() == pid and sigint(*x))
disable_signal_on_children(signal.SIGINT)

for name in "gateway router machine0 machine1".split():
    globals()[name] = node = nemu.Node()
    node.name = name
    node._screen = node.Popen((SCREEN, '-DmS', name))
    node.screen = (lambda name: lambda *cmd:
        subprocess.call([SCREEN, '-r', name, '-X', 'eval'] + map(
            "screen sh -c '%s; exec $SHELL'".__mod__, cmd)))(name)
    # WKRD: Why does the kernel (3.5.3) do SLAAC in separate network stacks
    #       whereas forwarding=0 and accept_ra=1 ? Force autoconf ...
    node.system('sysctl net.ipv6.conf.default.accept_ra=2')

r0, m0 = nemu.P2PInterface.create_pair(router, machine0)

switch = nemu.Switch()
gw = nemu.NodeInterface(gateway);  switch.connect(gw)
r1 = nemu.NodeInterface(router);   switch.connect(r1)
m1 = nemu.NodeInterface(machine1); switch.connect(m1)

router.system('brctl addbr br0 && brctl addif br0 %s' % r0.name)
br = router.get_interface('br0')

switch.up = gw.up = br.up = r0.up = r1.up = m0.up = m1.up = 1
for a in gw.get_addresses():
    a = a['address']
    if a.startswith('fe80:'):
        router.add_route(nexthop=a, interface=r1)
        break
br.add_v6_address(address='2001:db8:42:3::1', prefix_len=64)
r1.add_v6_address(address='2001:db8:1:2::3', prefix_len=64)

router.screen('dnsmasq -d8 - -i %s -F 2001:db8:42:3::,ra-only,64,1d' % br.name)

import pdb; pdb.set_trace()
