#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-hostname
# BEFORE: hostname

. /etc/rc.freenas

generate_hostname()
{
	local IFS="|"
	local f="id gc_hostname gc_domain"
	eval local $f
	local sf=$(var_to_sf $f)
	${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
	"SELECT $sf FROM network_globalconfiguration ORDER BY -id LIMIT 1" | \
	while eval read -r $f; do
		cp /conf/base/etc/hosts /etc/hosts
	${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "SELECT gc_hosts FROM network_globalconfiguration WHERE id = ${id}" >> /etc/hosts
	done

	if dirsrv_enabled nis; then
		echo nis >> /etc/host.conf
		echo "${NIS_HOSTSSTR}" >> /etc/hosts
	elif dirsrv_enabled activedirectory; then
		local domainname
		local netbiosname

		${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
		"SELECT ad_domainname, ad_netbiosname from directoryservice_activedirectory ORDER BY -id LIMIT 1" | \
		while read -r domainname netbiosname; do
			netbiosname="$(echo "${netbiosname}"|cut -f1 -d','|cut -f1 -d ' '|tr A-Z a-z)"
			domainname="$(echo "${domainname}"|tr A-Z a-z)"

			echo -e "127.0.0.1\t"${netbiosname}" "${netbiosname}.${domainname}"" >> /etc/hosts
		done
	else
		local tmpfile="$(mktemp /tmp/.XXXXXX)"
		grep -Ev '^nis' /etc/host.conf > "${tmpfile}" 2> /dev/null
		mv "${tmpfile}" /etc/host.conf
		chmod 644 /etc/host.conf
	fi
}

name="ix-hostname"
start_cmd='generate_hostname'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
