#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2011, P. Lutus
# Released under the GPL
# http://www.gnu.org/copyleft/gpl.html

import re,sys,os
    
def write_file(path,data):
  with open(path,'w') as f:
    f.write(data)

def capture_com_output(com):
  with os.popen(com) as p:
    return p.read()

if(os.geteuid() != 0):
  print "Must be root to run this script."
  sys.exit(0)
  
path='/etc/udev/rules.d/99-old-style-net.rules'

if os.path.exists(path):
  print 'Configuration file %s already exists, quitting.' % path
  sys.exit(0)

data = capture_com_output('ip link show')

search_str = '(em\\d|p\\d+p\\d)'

if not re.match('(?s).*%s.*' % search_str,data):
  print 'Interface name not found with %s, quitting.' % search_str
  sys.exit(0)

mac_address = re.sub('(?s).*?\n?%s:.*?link/ether\\s+(\\S+).*?\n.*' % search_str,'\\2',data)

data =  'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", KERNEL=="eth*", '
data += 'ATTR{address}=="%s", NAME="eth0"\n' % mac_address

write_file(path,data)

print 'Created %s.' % path

reply = raw_input('This change requires a system reboot. OK to reboot? (y/N): ')

reply.strip().lower()

if(reply == 'y'):
  os.system('init 6')
