#!/bin/bash function set_hostname() { hostname=$1 if [ -d /run/systemd/system/ ]; then hostnamectl set-hostname --static "${hostname}" else if [ -f /etc/sysconfig/network ]; then sed -i '/^HOSTNAME=.*$/d' /etc/sysconfig/network echo "HOSTNAME=${hostname}" >>/etc/sysconfig/network else echo "${hostname}" >/etc/hostname fi hostname "${hostname}" fi } function set_domainname() { domain=$1 sed -i '/^domain .*/d' /etc/resolv.conf echo "domain ${domain}" >>/etc/resolv.conf } function get_first_ip() { hostname -I | cut -d' ' -f1 } function get_dns_name() { text=$(LC_ALL=C host "$1" 2>/dev/null) [ $? = 0 ] || exit 0 [[ $text == *"has no PTR record" ]] && exit 0 name=$(echo "$text" | awk '/(has address|name pointer)/ {print $(NF)}' | sed 's/\.$//') echo $name } function update_hosts() { ip=$1 name=$2 hostname=$3 if [ "x${hostname}" = "x${name}" ]; then hosts="${name}" else hosts="${name} ${hostname}" fi note='# one-contextd' entry="${ip}\t${hosts}\t\t${note}" # update our old entry if grep -qi "${note}" /etc/hosts; then sed -i -e "s/^.*${note}\$/${entry}/" /etc/hosts # update entry with same IP (but not localhost) elif grep -E "^${ip}\s" /etc/hosts | grep -qv localhost; then sed -i -e "/localhost/! s/^${ip}\s.*\$/${entry}/" /etc/hosts # update entry with same name elif grep -qE "\s${name}(\s|#|\$)" /etc/hosts; then sed -i -re "s/^.*\s${name}([ #\t].*|$)/${entry}/" /etc/hosts # create new entry elif [ -f /etc/hosts ]; then sed -i -e "1s/^/${entry}\n/" /etc/hosts else echo -e "${entry}" >>/etc/hosts fi } ##### first_ip=$(get_first_ip) if [ -n "$SET_HOSTNAME" ]; then name=$(echo "$SET_HOSTNAME" | \ sed -e 's/[^-a-zA-Z0-9\.]/-/g' -e 's/^-*//g' -e 's/-*$//g') elif [ -n "$DNS_HOSTNAME" ]; then name=$(get_dns_name "${first_ip}") fi if [ -n "${name}" ]; then # split host and domain names hostname=${name%%.*} domain=${name#*.} if [ "x${domain}" = "x${hostname}" ]; then domain='' fi set_hostname "${hostname}" if [ -n "${domain}" ]; then set_domainname "${domain}" fi if [ -n "${DNS_HOSTNAME}" ]; then host_ip=$first_ip else # If selected hostname resolves on first IP, # use first IP for local hostname in /etc/hosts. # Otherwise use loopback IP. name_ip=$(get_dns_name "${name}") if [ "x${first_ip}" = "x${name_ip}" ]; then host_ip=$first_ip elif [ -f /etc/debian_version ]; then host_ip='127.0.1.1' else host_ip='127.0.0.1' fi fi if [ -n "${host_ip}" ]; then update_hosts "${host_ip}" "${name}" "${hostname}" fi fi