#!/bin/bash

BASE="10.4"
LEAF="1"
SERVER="1"

function guess_type {
    local CNT=$(echo "$1" | sed -e 's/[:.]/ /g' | wc -w)
    if [ $CNT -ne 1 ]; then
        # drop all sub and vlan interfaces
        echo "DNC"
        return
    fi
    local DRIVER=$(ethtool -i $1 2>/dev/null | grep driver | awk '{print $2}')
    local RESULT="DNC"
    case $DRIVER in
        i40e)
            RESULT="I40G"
            ;;
        igb)
            RESULT="ETH"
            ;;
        *) ;;
    esac
    echo $RESULT
}

function get_mac {
  echo $(ifconfig $1 | grep HWaddr | awk '{print $5}')
}

function generate_persistent_names {
    local OUT="70-persistent-net.rules"
    rm -rf $OUT

    IDX=0
    for i in $(cat $1 | sort); do
        echo "SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS==\"?*\", ATTR{address}==\"$i\", ATTR{dev_id}==\"0x0\", ATTR{type}==\"1\", KERNEL==\"eth*\", NAME=\"eth$IDX\"" >> $OUT
        IDX=$(expr $IDX + 1)
    done

    for i in $(cat $2 | sort); do
        echo "SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS==\"?*\", ATTR{address}==\"$i\", NAME=\"eth$IDX\"" >> $OUT
        IDX=$(expr $IDX + 1)
    done
}

function generate_interfaces {
    OUT="interfaces"
    rm -rf $OUT
    echo "# This file describes the network interfaces available on your system" >> $OUT
    echo "# and how to activate them. For more information, see interfaces(5)." >> $OUT
    echo "" >> $OUT
    echo "# The loopback network interface" >> $OUT
    echo "auto lo" >> $OUT
    echo "iface lo inet loopback" >> $OUT
    echo "" >> $OUT

    IDX=0
    FIRST=1
    for i in $(cat $1); do
        if [ $FIRST -eq 1 ]; then
            echo "auto eth$IDX" >> $OUT
            echo "iface eth$IDX inet static" >> $OUT
            echo "    address $BASE.$LEAF.$SERVER" >> $OUT
            echo "    network $BASE.$LEAF.0" >> $OUT
            echo "    netmask 255.255.255.0" >> $OUT
            FIRST=0
        else
            echo "iface eth$IDX inet manual" >> $OUT
        fi
        echo "" >> $OUT
        IDX=$(expr $IDX + 1)
    done

    FIRST=1
    for i in $(cat $2); do
        if [ $FIRST -eq 1 ]; then
            echo "auto eth$IDX" >> $OUT
            echo "iface eth$IDX inet dhcp" >> $OUT
            FIRST=0
        else
            echo "iface eth$IDX inet manual" >> $OUT
        fi
        echo "" >> $OUT
        IDX=$(expr $IDX + 1)
    done
}

LIST_ETH=$(mktemp -u)
LIST_40G=$(mktemp -u)
IFACES=$(ifconfig -a | grep "^[a-z]" | awk '{print $1}')

for i in $IFACES; do
    TYPE=$(guess_type $i)
    case $TYPE in
        ETH)
            echo "$(get_mac $i)" >> $LIST_ETH
            ;;
        I40G)
            echo "$(get_mac $i)" >> $LIST_40G
            ;;
        *) ;;
    esac
done

generate_persistent_names $LIST_40G $LIST_ETH
generate_interfaces $LIST_40G $LIST_ETH
rm -rf $LIST_ETH
rm -rf $LIST_40G
