#!/bin/bash
#

######## I check ips.txt file input 
BASEDIR=$(dirname "$0")
file="$BASEDIR/ips.txt"
if [ -f "$file" ]
then
    ips=`cat $BASEDIR/ips.txt`
else
    echo "ips.txt file not found."1>&2;
    exit 1
fi
####### I end #################
####### II : check if we pass ip as argument
if [ $# -eq 0 ]
  then
    echo "No arguments IP"
    exit 1
fi
main_ip=$1
####### II end #################
####### III :  check if the ip provided exists in some interface
fileint_name="$(grep -il $main_ip /etc/sysconfig/network-scripts/ifcfg-* | head -1)"
if [[ ! -f "${fileint_name}" ]]
then
        echo "couldnt find interface with ip : $1" 1>&2;
        exit 1
fi
####### III end #################
####### IV : ips already configured
echo "main ip : $main_ip"
# les ip deja configure
ifconfig |grep "inet " | awk '{print $2}'| tee existsips.txt
echo "Current IPs :"
cat existsips.txt
####### IV end ##################
####### V :  count existing interfaces (i), so we begin from 'i+1'
ls /etc/sysconfig/network-scripts/ | grep ifcfg- | awk -F '-' '{print $2}' | grep -v 'lo' | tee  tmp_name.txt # list :interfaces names
max_int=`awk -F ':' '{print $2}' tmp_name.txt | sort -n | tail -1`
i=`expr $max_int + 1`    #interface nbr to start with
rm -f tmp_name.txt
####### V  end ###################
# interface name ex: eno7845, p4p2, eth0
int_name=$(echo "$fileint_name" | awk -F '/' '{print $5}' | awk -F '-' '{print $2}')
####### VI : Configur interfaces #
for ip in $ips
do
    if [[ `grep $ip existsips.txt` != $ip ]];
    then        
        destination_file="$fileint_name:$i"
        cp $fileint_name $destination_file
        sed -i 's/NAME=.*$/NAME='"${int_name}:$i"'/g' $destination_file
        sed -i 's/DEVICE.*$/DEVICE='"$int_name:$i"'/g' $destination_file
        sed -i 's/IPADDR.*$/IPADDR=\"'$ip'\"/g' $destination_file
        sed -i 's/BOOTPROTO=.*$/BOOTPROTO=static/g' $destination_file
        sed -i 's/ONBOOT=.*$/ONBOOT=yes/g' $destination_file
        sed -i 's/UUID=.*$/#removed UUID/g' $destination_file
        let i++
        echo "$ip -> $destination_file "
    fi
done
####### VI : end configurations # 
rm -f existsips.txt
echo "cleaning ... Done"
service network restart
####### by mtk # 