#!/bin/bash
# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
### BEGIN INIT INFO
# Provides:          openvz-fix-etchosts
# Required-Start:    $network
# Required-Stop:     
# Should-Start:      
# Should-Stop:       
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: fix /etc/hosts in openvz containers
# Description:       fix /etc/hosts for services (e.g. slapd) which need that
#                    the local hostname does *not* resolve to localhost. In
#                    practice, remove hostname from the line
#                      127.0.0.1 hostname localhost localhost.localdomain
#                    in /etc/hosts
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
LANG=fr_FR.UTF-8
export PATH LANG

. /lib/lsb/init-functions

function is_openvz_ct() {
    local ctid="$(grep envID /proc/self/status | awk '{print $2}')"
    [ -n "$ctid" -a "$ctid" != "0" ]
}

function fix_etchosts() {
    local host hostname ip

    # supprimer hostname --> 127.0.0.1
    hostname="$(</etc/hostname)"
    sed -i '/^\(127.0.0.1\|::1\)/s/'"$hostname"'\(\.[^ \t]*\)\?[ \t]*//g' /etc/hosts

    # ajouter host hostname --> ip
    host="$(hostname -f 2>/dev/null)"
    hostname="$(hostname -s 2>/dev/null)"
    local ip="$(LANG=C host "$host" 2>/dev/null | awk '/address / { gsub(/^.*address /, ""); print }' | head -n1)"
    if [ -n "$ip" ] && ! grep -Fq "$ip" /etc/hosts; then
        echo "$ip $host $hostname" >>/etc/hosts
    fi
}

case "$1" in
start)
    if is_openvz_ct; then
        log_action_msg "Fixing /etc/hosts..."
        fix_etchosts
        log_end_msg 0
    fi
    ;;
stop)
    ;;
*)
    log_action_msg "Usage: /etc/init.d/$NAME start"
    exit 1
    ;;
esac

exit 0