#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org

START=99

NAME=ahcpd
BIN_F=/usr/sbin/$NAME
SSD=start-stop-daemon

is_enabled() {
	local cfg="$1"

	config_get_bool enabled "$cfg" enabled '1'
	[ $enabled -ne 0 ] || {
		echo "$initscript: not enabled"
		return 1
	}
}

get_interface() {
	local cfg="$1"

	config_get interface "$cfg" interface
	[ -n "$interface" ] || {
		echo "$initscript: not 'interface' option specified"
		return 1
	}
}

get_pid_file() {
	local cfg="$1"

	config_get pid_file "$cfg" pid_file
	[ -n "$pid_file" ] || pid_file="/var/run/$NAME-$interface.pid"
}

get_options() {
	local cfg="$1"
	local address
	local port
	local authoritative

	config_get options "$cfg" options

	config_get config_script "$cfg" config_script
	[ -n "$config_script" ] && append options "-c $config_script"

	config_get address "$cfg" address
	[ -n "$adress" ] && append options "-m $address"

	config_get port "$cfg" port
	[ -n "$port" ] && append options "-p $port"

	config_get_bool authoritative "$cfg" authoritative '0'
	[ $authoritative -ne 0 ] && {
		local dat_file
		local gen_options

		config_get dat_file "$cfg" authority_file
		[ -n "$dat_file" ] || dat_file="/var/run/$NAME-$interface.dat"

		[ -f "$dat_file" ] || {
			local expire
			local prefix
			local prototocol
			local dns_server
			local ntp_server

			config_get prefix "$cfg" prefix
			[ -n "$prefix" ] || prefix=`ahcp-generate-address -p -s -r`
			append gen_options "-p $prefix"

			config_get expire "$cfg" expire
			[ -n "$expire" ] && append gen_options "-e $expire"

			config_get protocol "$cfg" protocol
			[ -n "$protocol" ] && append gen_options "-P $protocol"

			[ "$protocol" = "static" ] && {
				local gateway

				config_get gateway "$cfg" gateway
				[ -n "$gateway" ] && append gen_options "-g $gateway"
			}

			config_get dns_server "$cfg" dns_server
			[ -n "$dns_server" ] && append gen_options "-n $dns_server"

			config_get ntp_server "$cfg" ntp_server
			[ -n "$ntp_server" ] && append gen_options "-N $ntp_server"

			ahcp-generate $gen_options > $dat_file
		}
		append options "-a $dat_file"
	}
	append options "$interface"
}

start_service() {
	local cfg="$1"

	is_enabled "$cfg" || return
	get_interface "$cfg" || return
	get_pid_file $cfg
	get_options $cfg

	$SSD -S -p $pid_file -b -m -x $BIN_F -- $options &>/dev/null
}

stop_service() {
	local cfg="$1"

	is_enabled "$cfg" || return
	get_interface "$cfg" || return
	get_pid_file $cfg

	$SSD -K -p $pid_file &>/dev/null
}

start() {
	config_load $NAME
	config_foreach start_service $NAME
}

stop() {
	config_load $NAME
	config_foreach stop_service $NAME
}

