#!/bin/bash

NETMASK="255.255.255.0"
INTERFACE="eth0"

function bringup()
{
        find /etc/sysconfig/network-scripts/ -name "ifcfg-$INTERFACE:*" -print0|xargs -0 -n 1 echo | awk -F"/" '{ print $5 }' | awk -F"-" '{ print $2 }' | while read ifcfg_eth; do

                IPADDR=`grep -Ei "IPADDR=" /etc/sysconfig/network-scripts/ifcfg-$ifcfg_eth | awk -F"=" '{ print $2 }'`
                echo "IPADDR: $IPADDR"
                echo "ifconfig $ifcfg_eth down"
                ifconfig $ifcfg_eth down
                echo "ifcfg_eth: $ifcfg_eth with IPADDR: $IPADDR"
                ifconfig $ifcfg_eth inet $IPADDR netmask $NETMASK
        done
}

function bringup_ips_text()
{
        while read IPADDR; do
                echo "IPADDR: $IPADDR"
                ifcfg=`grep -Ei "$IPADDR" /etc/sysconfig/network-scripts/ifcfg-$INTERFACE:* | awk -F "eth0:" '{ print $2 }' | awk -F ":" '{ print $1 }'`
                echo "ifconfig $INTERFACE:$ifcfg down"
                ifconfig $INTERFACE:$ifcfg down
                if [[ $1 == "new_if_up_approach" ]]; then
                        echo "inside new approach"
                        ifconfig $INTERFACE:$ifcfg inet $IPADDR netmask $NETMASK
                else
                        ifup $INTERFACE:$ifcfg
                fi
        done < ips.txt
}

function repair_the_mess()
{
        find /etc/sysconfig/network-scripts/ -name "ifcfg-$INTERFACE:*" -print0|xargs -0 -n 1 echo | awk -F"/" '{ print $5 }' | awk -F"-" '{ print $2 }' | while read ifcfg_eth; do

                IPADDR=`grep -Ei "IPADDR=" /etc/sysconfig/network-scripts/ifcfg-$ifcfg_eth | awk -F"=" '{ print $2 }'`

                if [[ `ping $IPADDR -c 1 | grep "nexthop"` ]]; then
                        echo "we found dead IP with: $IPADDR"
                        ifconfig $ifcfg_eth down
                        ifconfig $ifcfg_eth inet $IPADDR netmask $NETMASK
                fi
        done
}

if [ $# -ne 0 -a $# -eq 1 ]; then
        bringup_ips_text
elif [ $# -ne 0 -a $# -eq 2 ]; then
        bringup_ips_text "new_if_up_approach"
else
        bringup
fi
#repair_the_mess
