#!/bin/bash
# Copyright (c) 2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

# Contributed by Roy Marples <uberlord@gentoo.org>

system_get_vars() {
	echo "dns_servers_$1 dns_domain_$1 dns_search_domains_$1 ntp_servers_$1 nis_domain_$1 nis_servers_$1"
}

system_dns() {
	local x

	# Nameserver setup for the essid if required
	local -a servers
	eval servers='( "${dns_servers_'${ifvar}'[@]}" )'
	[[ -z ${servers} ]] && return 0

	echo "# Generated by net-scripts system module" > /etc/resolv.conf.tmp
	chmod 644 /etc/resolv.conf.tmp

	eval x=\"\$\{dns_domain_${ifvar}\}\"
	[[ -n ${x} ]] && echo "domain ${x}" >> /etc/resolv.conf.tmp

	for x in ${servers[@]}; do
		echo "nameserver ${x}" >> /etc/resolv.conf.tmp
	done

	eval x=\"\$\{dns_search_domains_${ifvar}\}\"
	[[ -n ${x} ]] && echo "search ${x}" >> /etc/resolv.conf.tmp

	[[ -f /etc/resolv.conf && ! -f /etc/resolv.conf.sv ]] \
		&& mv /etc/resolv.conf /etc/resolv.conf.sv
	mv /etc/resolv.conf.tmp /etc/resolv.conf
}

system_ntp() {
	local x
	local -a servers

	eval servers='( "${ntp_servers_'${ifvar}'[@]}" )'
	[[ -z ${servers} ]] && return 0

	echo "# generated automatically by net-scripts" > /etc/ntp.conf.tmp
	chmod 644 /etc/ntp.conf.tmp

        echo "restrict default noquery notrust nomodify" >> /etc/ntp.conf.tmp
	echo "restrict 127.0.0.1" >> /etc/ntp.conf.tmp
	echo "driftfile /var/lib/ntp/ntp.drift" >> /etc/ntp.conf.tmp

	for x in ${servers[@]}; do
		echo "restrict ${x} nomodify notrap noquery" >> /etc/ntp.conf.tmp
		echo "server ${x}" >> /etc/ntp.conf.tmp
	done

	[[ -f /etc/ntp.conf && ! -f /etc/ntp.conf.sv ]] \
		&& mv /etc/ntp.conf /etc/ntp.conf.sv
	mv /etc/ntp.conf.tmp /etc/ntp.conf
}

system_nis() {
	local domain x
	local -a servers

	eval servers='( "${nis_servers_'${ifvar}'[@]}" )'
	eval domain=\"\$\{nis_domain_${ifvar}\}\"
	[[ -z ${servers} && -z ${domain} ]] && return 0

	echo "# generated automatically by net-scripts" > /etc/yp.conf.tmp
	chmod 644 /etc/yp.conf.tmp

	if [[ -n ${domain} ]]; then
		/bin/hostname -y ${domain}
		if [[ -n ${servers} ]]; then
			for x in ${servers}; do
				echo "domain ${domain} server ${x}" >> /etc/yp.conf.tmp
			done
		else
			echo "domain ${domain} broadcast" >> /etc/yp.conf.tmp
		fi
	else
		for x in ${servers}; do
			echo "ypserver ${x}" >> /etc/yp.conf.tmp
		done
	fi

	[[ -f /etc/yp.conf && ! -f /etc/yp.conf.sv ]] && mv /etc/yp.conf /etc/yp.conf.sv
	mv /etc/yp.conf.tmp /etc/yp.conf
}

system_start() {
	system_dns
	system_ntp
	system_nis
}
