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

# PROVIDE: ix-hostname
# BEFORE: hostname

. /etc/rc.freenas

generate_hostname()
{
	local IFS="|"
	local id gc_hostname gc_domain hostname_field

	if [ "$(ha_node)" = "B" ]; then
		hostname_field="gc_hostname_b"
	else
		hostname_field="gc_hostname"
	fi

	id="$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
            "SELECT id FROM network_globalconfiguration ORDER BY -id LIMIT 1")"
	gc_hostname="$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
            "SELECT ${hostname_field} FROM network_globalconfiguration ORDER BY -id LIMIT 1")"
	gc_domain="$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
            "SELECT gc_domain FROM network_globalconfiguration ORDER BY -id LIMIT 1")"

	cp /conf/base/etc/hosts /etc/hosts
	${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
		"SELECT gc_hosts FROM network_globalconfiguration WHERE id = ${id}" >> /etc/hosts

	if dirsrv_enabled nis; then
		echo -e "127.0.0.1\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo -e "::1\t\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo nis >> /etc/host.conf
		echo "${NIS_HOSTSSTR}" >> /etc/hosts
	elif dirsrv_enabled activedirectory; then
		local domainname
		local netbiosname
		local netbiosname_field

		if [ "$(ha_node)" = "B" ]; then
			netbiosname_field="ad_netbiosname_b"
		else
			netbiosname_field="ad_netbiosname_a"
		fi

		${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
		"SELECT ad_domainname, ${netbiosname_field} 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}.${domainname}" "${netbiosname}"" >> /etc/hosts
			echo -e "::1\t\t"${netbiosname}.${domainname}" "${netbiosname}"" >> /etc/hosts
		done
	else
		echo -e "127.0.0.1\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo -e "::1\t\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		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"
