#!/usr/bin/python

import sys,os

def clean_chain(iface, mac, chain):
  p = os.popen('ebtables -L %s | grep %s' % (chain, mac))
  for x in p.readlines():
    os.system('ebtables -D %s -i %s -s %s -j ACCEPT' % (chain, iface, mac))
  p.close()
 
def clean_mac(iface, mac):
  clean_chain(iface, mac, 'FORWARD')
  clean_chain(iface, mac, 'INPUT')

try:
  op = sys.argv[1]
  if not op in ['-a','-p','-b','-i']:
    raise ValueError('Invalid option %s' % op)
  if op in ['-p','-b']:
    mac = sys.argv[2]
    iface = sys.argv[3]
except:
  print 'Use: %s {-p|-b} MAC IFACE | -i | -a' % sys.argv[0]
  sys.exit(1)

open('/tmp/log','a').write('%s\n' % sys.argv)

if op == '-i':
  l = os.popen('ebtables -L INPUT | grep 0x888e').readlines()
  for x in l:
    os.system('ebtables -D INPUT -p 0x888e -j ACCEPT > /dev/null 2>&1')
  os.system('ebtables -P FORWARD DROP; ebtables -P INPUT DROP; ebtables -A INPUT -p 0x888e -j ACCEPT')
elif op == '-a':
  os.system('ebtables -P FORWARD ACCEPT; ebtables -P INPUT ACCEPT')
else:
  port=os.popen('brctl showmacs %s | grep %s' % (iface, mac)).readline()
  port=port.split()[0]
  iface = os.popen('brctl showstp %s | egrep -o "^eth[0-9]+ \(%s\)"' % (iface, port)).readline()
  iface = iface.split()[0]

  if op == '-p':
    clean_mac(iface, mac)
    os.system('ebtables -A FORWARD -i %s -s %s -j ACCEPT; ebtables -A INPUT -i %s -s %s -j ACCEPT' % (iface, mac, iface, mac))
  else:
    clean_mac(iface, mac)

sys.exit(0)
