#!/usr/bin/python

""" Swap the physical HW used for eth1 and eth0.

    Author: Martin Langhoff <martin@laptop.org>
    Copyright: One Laptop per Child
    License: GPLv2
"""

import re, os, os.path, tempfile, sys, subprocess

RULESFILE='/etc/udev/rules.d/70-persistent-net.rules'

if not os.path.exists(RULESFILE):
    sys.stderr.write('No rules file!')
    sys.exit(1)

(destfh, tmpfile) = tempfile.mkstemp()
srcf = file(RULESFILE, 'r')

eth0 = re.compile('(?<=NAME=")eth0(?=")')
eth1 = re.compile('(?<=NAME=")eth1(?=")')

for line in srcf:

    (dstline, hits) = eth0.subn('eth1', line)
    if hits > 0:
        os.write(destfh, dstline)
        continue
    (dstline, hits) = eth1.subn('eth0', line)
    if hits > 0:
        os.write(destfh, dstline)
        continue
    os.write(destfh, line)

srcf.close()
os.close(destfh)

os.chdir('/etc')
subprocess.call(['etckeeper', 'commit', '-m', 'xs-swapnics pre: Dirty state'])
subprocess.check_call(['mv', tmpfile, RULESFILE])
subprocess.check_call(['etckeeper', 'commit', '-m', 'xs-swapnics: updated'])

