#!/bin/bash

# For main Ethernet interface (i.e. eth0) we insert an entry in
# /etc/hosts so that resolutions of our own hostname do not
# depend on a DNS server being available.

[ -n "$IFACE" ] || exit 1

# Skip if not inet
[ "$ADDRFAM" = "inet" ] || exit 0

# Skip if not eth0
[ "$IFACE" = "eth0" ] || exit 0

# Skip if zeroconf, we do not want to associate the hostname with
# a zeroconf address (we leave that for the main address)
[ "$METHOD" = "zeroconf" ] && exit 0

# Make sure we have a hostname
host="$(hostname)"
[ $? -eq 0 ] || exit 1
[ -n "$host" ] || exit 0

# Recover the IP address of the interface
# (avoid aliases by using the label)
addr="$(ip -f inet addr show dev "$IFACE" label "$IFACE" | sed -e 's|^[[:space:]]\+inet[[:space:]]\+\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*|\1|p;d')"
[ $? -eq 0 ] || exit 1
if [ ! -n "$addr" ]; then
    echo "No IP address on '$IFACE' to set for '${host}' in /etc/hosts" >&2
    exit 0
fi

# Add / replace hostname entry in /etc/hosts (the file is atomically updated)

tmphosts=$(mktemp /etc/hosts.XXXXXX)
[ $? -eq 0 ] || exit 1
chmod 644 $tmphosts

grep -v -P "\b${host}\b" /etc/hosts >> $tmphosts
echo "$addr" "$host" >> $tmphosts

mv -f $tmphosts /etc/hosts

# Make the address visible in the logs
echo "Set IP ${addr} on '$IFACE' for '${host}' in /etc/hosts"

exit 0
