#!/bin/bash

ALIAS_SDN_BIN=./alias_sdn.sh 

if [ ! -r "$ALIAS_SDN_BIN" ] ; then 
   echo "ALIAS_SDN_BIN not found in $ALIAS_SDN_BIN"
   exit 1
fi

_check_resolution() {
  local hostname="$1"
  local ip=$2
  local main_hostname=${3:-""}
  local has_ip=""
  has_ip=$(grep "$ip" /etc/hosts | grep -v "^#" | awk '{print $1}')
  [ -z "$has_ip" ] && echo "$ip ${hostname}" | sudo tee -a /etc/hosts 2>/dev/null >/dev/null
  if [ "$main_hostname" == "true" ] && [ "$hostname" !=  "$(cat /etc/hostname)" ] ; then
    echo "$hostname" | sudo tee /etc/hostname 2>/dev/null >/dev/null
    sudo hostname "$hostname"
  fi
}

[ -r "./env-ip-aliases"  ] && . ./env-ip-aliases

NET_INTERFACES=/etc/network/interfaces

{% if taskserv.aliases %}
{%- for ip in taskserv.aliases %} 
has_ip=$(grep {{ip.address}}  $NET_INTERFACES) 
if [ -z "$has_ip" ] ; then 
echo "
auto {{ip.dev_interface}}
iface {{ip.dev_interface}} inet static
address {{ip.address}} 
netmask {{ ip.netmask }}
{% if ip.search and ip.nameservers != "" -%}
dns-nameserver {{it}}
{% endif %}
{% if ip.search and ip.search != "" -%}
search {{ ip.search }}
{% endif %}
" | sudo tee -a  $NET_INTERFACES &>/dev/null
#export SETUP_MODE={{ ip.setup_mode }}
#export INTERFACE={{ ip.interface }}
#export DEV_INTERFACE={{ ip.dev_interface }}
#export NETMASK={{ ip.netmask }}
#$ALIAS_SDN_BIN up {{ ip.address }} 
_check_resolution {{ ip.hostname }} {{ ip.address }} {{ ip.main_hostname }}
fi
{% endfor %}
sudo systemctl restart networking
{% endif %}

#sudo cp $ALIAS_SDN_BIN /etc

