#!/bin/bash
# This works only in the manual interfaces.
if [ $# -ne 1 ]; then
    echo "Incorrect args"
    exit 1
fi
interface=$1
echo "WARNIING: This is working only bring the manual interfaces up, it might miss the other network interfaces. Please do not use it"
echo "Bringnig interface $interface up."
pushd /etc/systemd/network
filename=`ls *$interface*.network.manual`
if [[ -z  $filename ]] ; then
	echo "Can not find interface name"
	exit 1
fi

# Trying to parse the address from the file
while read line
do 
    key=`echo $line | cut -d'=' -f1`
    if [ "$key" = "Address" ]
    then 
        address=`echo $line | cut -d'=' -f2 | cut -d'/' -f1`
    fi 
done < $filename

#flush the adress
ip addr flush $interface

#Bring the interface up
ip link set dev $interface up

#Check for duplicates
arping -D -q -I $interface -c 2 $address
retval=$?
if [ $retval -ne 0 ] ; then
        # fail to obtain the ip
        echo "IP already exists in the network, will exit gracefully"
	exit 0
fi

echo "Everything is good, IP is not assigned elsewhere, will do the work"

newfilename="${filename%.*}"
mv $filename $newfilename
systemctl restart systemd-networkd
mv $newfilename $filename
popd

