#!/bin/bash

eth_up=`ip a | grep 'state UP' | awk {'print $2'} | perl -pe 's/:$//'`
if [ $eth_up = "eth0" ]; then
        echo "eth0 already active"
        exit 0
fi
if [ -z $eth_up ]; then
        echo "no active eth detected"
        exit 0
fi

RULES_DIR="/etc/udev/rules.d"
pref='NAME="'
patterns="s/$pref\eth0/$pref\eth_replace/; s/$pref$eth_up/$pref\eth0/; s/$pref\eth_replace/$pref$eth_up/"

echo "swap $eth_up with eth0"

for rule in $(ls $RULES_DIR/*.rules); do
        echo "processing $rule"
        sed -i "$patterns" $rule
done

sed -i "s/$eth_up/eth0/g" /etc/network/interfaces

if [ "$1" == "-r" ]; then
        echo "rebooting" && sleep 5 && reboot
fi
