#!/usr/bin/env bash

local_hostname=$(hostname)
local_ip=$(ip route get 1 | head -n 1 | grep -Eo "src\s*[0-9\.]*" | awk '{printf $2}')

if [ -z "${local_ip}" ]; then
    exit 1
fi
if [[ "${local_hostname}" == "localhost" || "${local_hostname}" == "localhost.localdomain" ]]; then
    exit 1
fi

# back-up old /etc/hosts
function backup_hosts(){
    cp -f /etc/hosts /etc/.hosts.bak
}

rst_hostname=$(cat /etc/hosts | grep -w ${local_hostname})
rst_vpcip=$(cat /etc/hosts | grep -w ${local_ip})

# only vpc ip changed
#if [[ -z $rst_vpcip ]] && [[ -n $rst_hostname ]]; then
if [[ -n ${rst_hostname} ]]; then
    if ! echo $rst_hostname | grep -qw $local_ip ; then
        backup_hosts
        sed -i "/\<${local_hostname}\>/d" /etc/hosts
        echo "${local_ip} ${local_hostname} ${local_hostname}" >> /etc/hosts
    fi
fi

# only hostname changed
#if [[ -n $rst_vpcip ]] && [[ -z $rst_hostname ]]; then
if [[ -n $rst_vpcip ]]; then
    if ! echo $rst_vpcip | grep -qw "$local_hostname" ; then
        backup_hosts
        sed -i "/\<${local_ip}\>/d" /etc/hosts
        echo "${local_ip} ${local_hostname} ${local_hostname}" >> /etc/hosts
    fi
fi

# both vpc ip & hostname changed
if [[ -z $rst_vpcip ]] && [[ -z $rst_hostname ]]; then
    backup_hosts
    echo "${local_ip} ${local_hostname} ${local_hostname}" >> /etc/hosts
fi
