Skip to content

Instantly share code, notes, and snippets.

@FlorianHeigl
Created November 16, 2016 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlorianHeigl/af4974cf988c97d25db7957fc2802d86 to your computer and use it in GitHub Desktop.
Save FlorianHeigl/af4974cf988c97d25db7957fc2802d86 to your computer and use it in GitHub Desktop.
cleaned up(?) script for deb
#!/bin/bash
. /tmp/context.sh
CONFIG_FILE="/etc/hostname"
function set_hostname() {
NAME=$1
[ -n "$NAME" ] || exit 0
echo $NAME > $CONFIG_FILE
hostname $OS_HOST_NAME
}
function get_dns_name() {
first_ip=$(hostname -I | cut -d' ' -f1)
text=$(host $first_ip)
[ $? = 0 ] || exit 0
[[ $text == *"has no PTR record" ]] && exit 0
name=$(echo "$text" | awk '{print $(NF)}' | sed 's/\.$//')
echo $name
}
function split_name() {
OS_HOST_NAME=$( echo $FOUND_NAME | cut -f1 -d\. )
DOMAIN=$( echo $FOUND_NAME | cut -f2- -d\. )
export OS_HOST_NAME DOMAIN
}
function set_hosts_entry() {
# eth0 should always be assigned
# so we'll use it's IP for the main hosts entry
if [[ -z ${ETH0_IP} ]]; then
return 1
else
hosts_entry="${ETH0_IP} ${FOUND_NAME} ${OS_HOST_NAME}"
fi
# if DNS is properly setup localhost will resolve from DNS
#if host localhost 2>&1 | grep ${DOMAIN} > /dev/null ; then
# localhost_entry="127.0.0.1 localhost.${DOMAIN} localhost"
#else
# update an ubuntu-style loopback entry
if grep ^127.0.1.1 /etc/hosts | grep -q -v localhost ; then
sed -i \
"s/127.0.1.1.*/127.0.1.1 ${FOUND_NAME} ${OS_HOST_NAME}/" \
/etc/hosts
fi
# do nothing if entry is as expected
if grep -q "$hosts_entry" /etc/hosts ; then
return 0
fi
# modify the actual entry for this host, ensure ip and host are OK
if grep -v ^# /etc/hosts | grep -v 127.0 | grep -q ${OS_HOST_NAME} ; then
sed -i \
"s/.*${OS_HOST_NAME}.*/${hosts_entry}/" \
/etc/hosts
else
echo $hosts_entry >> /etc/hosts
fi
}
function set_resolv_entry() {
# add the domain to resolver's infos, this allows for proper resolution
if ! grep -q -E "^domain.*$DOMAIN" /etc/resolv.conf ; then
echo "domain $DOMAIN" >> /etc/resolv.conf
fi
}
#get_name() {
# hostname could've been passed in via variables
if [ -n "$SET_HOSTNAME" ]; then
FOUND_NAME=${SET_HOSTNAME}
# or be derived from DNS
elif [ -n "$DNS_HOSTNAME" ]; then
FOUND_NAME=$(get_dns_name)
else
# or missing
exit 1
fi
export FOUND_NAME
#}
# get_name &&
split_name $FOUND_NAME &&
set_hostname $FOUND_NAME &&
set_resolv_entry &&
set_hosts_entry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment