#!/bin/sh



# funcs
#######
die(){
        TYPE="ERROR"
        if [ "$#" -gt 1 ] ; then
                TYPE="$1"
                shift
        fi
        printf "${TYPE}: " >&2
        while [ "$1" ] ; do
                echo "$1" >&2
                shift
        done
        echo "" >&2

        exit 1
}

dump_files(){
	# ignore files not ending in .host(s)
	ls -1 "$HOSTS_DIR" |sort |grep "\.host\(s\)\?$" |while read f ; do cat "$HOSTS_DIR/$f" ; done
}

remove_section(){
	 sed -i -e "/^$BEGIN_MARK$/,/^$END_MARK$/d" "$HOSTS_FILE"
}

add_section(){
	cat <<EOF
$BEGIN_MARK
# DO NOT EDIT THIS FILE BEETWEEN BEGIN/END MARKS
#
# This section of file is automatically generated by update-hosts using
# files from /etc/hosts.d
#
EOF
	dump_files
	echo "$END_MARK"
}

# vars
######
HOSTS_DIR="/etc/hosts.d"
HOSTS_FILE="/etc/hosts"
BEGIN_MARK="### BEGIN update-hosts section ###"
END_MARK="### END update-hosts section ###" 

# main
######

[ -w "$HOSTS_FILE" ] || die "Insufficient permissions to write hosts file: $HOSTS_FILE"
mkdir -p "$HOSTS_DIR"
[ -x "$HOSTS_DIR" ] || die "Unable to read hosts directory: $HOSTS_DIR"

remove_section
add_section >> "$HOSTS_FILE"

exit 0
