#!/bin/sh
#
# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.
#

# This script fixes up the /etc/hosts file to have an entry that maps to the
# local address if it is IPv6.

. /etc/clearwater/config

# If the local IP address is an IPv6 address then the system needs a dummy
# hostname that maps to the address.

# Remove any entries that have been previously added by this script.
grep -v '# added by clearwater-infrastructure 1hosts script' /etc/hosts | grep -v ' # maps to local IPv6 address' > /tmp/hosts.$$

# Determine whether the local IP address is an IPv6 address.
if /usr/share/clearwater/bin/is-address-ipv6 $local_ip
then
  # Generate the ip6.arpa hostname from the IP address.  Add it to the hosts file.
  hostname=$(/usr/share/clearwater/bin/ipv6-to-hostname $local_ip)
  echo $local_ip $hostname ' # added by clearwater-infrastructure 1hosts script' >> /tmp/hosts.$$
fi

# Append the IPv6 localhost.  This is to satisfy RFC6761 section 6.3, namely
# "Users may assume that IPv4 and IPv6 address queries for localhost names
# will always resolve to the respective IP loopback address."
echo '::1 localhost # added by clearwater-infrastructure 1hosts script' >> /tmp/hosts.$$

# Compare the new hosts file with the existing one.  If it has changed overwrite
# the existing file and restart dnsmasq to pick up the changes, otherwise just
# remove the new file.

if diff /etc/hosts /tmp/hosts.$$ > /dev/null ;
then
  rm /tmp/hosts.$$
else
  mv /tmp/hosts.$$ /etc/hosts
  service dnsmasq restart
fi
