#!/sbin/runscript
# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-x86/net-misc/dhcp/files/dhcpd.init3,v 1.1 2011/03/05 23:59:20 vapier Exp $

opts="configtest"

DHCPD_CONF=${DHCPD_CONF:-/etc/dhcp/${SVCNAME}.conf}

depend() {
	need net
	use logger dns
}

get_var() {
	sed -n 's/^[[:blank:]]\?'"$1"' "*\([^#";]\+\).*/\1/p' \
		"${DHCPD_CHROOT}/${DHCPD_CONF}"
}

checkconfig() {
	dhcpd ${DHCPD_OPTS} ${DHCPD_CHROOT:+-chroot} ${DHCPD_CHROOT} -t 1>/dev/null 2>&1
	local ret=$?
	if [ $ret -ne 0 ] ; then
		eerror "${SVCNAME} has detected a syntax error in your configuration files:"
		dhcpd ${DHCPD_OPTS} ${DHCPD_CHROOT:+-chroot} ${DHCPD_CHROOT} -t
	fi

	return $ret
}

configtest() {
	ebegin "Checking ${SVCNAME} configuration"
	checkconfig
	eend $?
}

start() {
	# Work out our cffile if it's in our DHCPD_OPTS
	case " ${DHCPD_OPTS} " in
		*" -cf "*)
			DHCPD_CONF=" ${DHCPD_OPTS} "
			DHCPD_CONF="${DHCPD_CONF##* -cf }"
			DHCPD_CONF="${DHCPD_CONF%% *}"
			;;
		*)	DHCPD_OPTS="${DHCPD_OPTS} -cf ${DHCPD_CONF}"
			;;
	esac

	if [ ! -f "${DHCPD_CHROOT}/${DHCPD_CONF}" ] ; then
		eerror "${DHCPD_CHROOT}/${DHCPD_CONF} does not exist"
		return 1
	fi

	checkconfig || return 1

	checkpath -d -o dhcp:dhcp /var/run/dhcp /var/lib/dhcp

	local leasefile="$(get_var lease-file-name)"
	leasefile="${leasefile:-/var/lib/dhcp/${SVCNAME}.leases}"
	if [ ! -f "${DHCPD_CHROOT}${leasefile}" ] ; then
		ebegin "Creating ${leasefile}"
		touch "${DHCPD_CHROOT}${leasefile}"
		chown dhcp:dhcp "${DHCPD_CHROOT}${leasefile}"
		eend $? || return 1
	fi

	# Setup LD_PRELOAD so name resolution works in our chroot.
	if [ -n "${DHCPD_CHROOT}" ] ; then
		LD_PRELOAD="${LD_PRELOAD} /usr/lib/libresolv.so"
		export LD_PRELOAD="${LD_PRELOAD} /usr/lib/libnss_dns.so"
	fi

	local pidfile="$(get_var pid-file-name)"
	pidfile="${pidfile:-/var/run/dhcp/${SVCNAME}.pid}"

	ebegin "Starting ${DHCPD_CHROOT:+chrooted }${SVCNAME}"
	start-stop-daemon --start --exec /usr/sbin/dhcpd \
		--pidfile "${DHCPD_CHROOT}/${pidfile}" \
		-- ${DHCPD_OPTS} -q -pf "${pidfile}" -lf "${leasefile}" \
		-user dhcp -group dhcp \
		${DHCPD_CHROOT:+-chroot} ${DHCPD_CHROOT} ${DHCPD_IFACE}
	eend $? \
		&& save_options chroot "${DHCPD_CHROOT}" \
		&& save_options pidfile "${pidfile}"
}

stop() {
	local chroot="$(get_options chroot)"
	
	ebegin "Stopping ${chroot:+chrooted }${SVCNAME}"
	start-stop-daemon --stop --exec /usr/sbin/dhcpd \
		--pidfile "${chroot}/$(get_options pidfile)"
	eend $?
}